我想以编程方式更改已禁用的JComboBox
上显示的所选项目。我试过了
setSelectedItem
之前启用它并在updateUI
可能这不是故意的,但是可以省去用JLabel
替换组合框的工作,所以也应该感谢肮脏的黑客答案。
答案 0 :(得分:3)
好吧,它似乎对我有用......
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JComboBox cb = new JComboBox(new String[]{
"One", "Two", "Three", "Four", "Five"
});
cb.setEnabled(false);
add(cb, gbc);
cb.setEnabled(false);
JButton btn = new JButton("Update");
add(btn, gbc);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cb.setSelectedItem("Five");
}
});
}
}
}
确保您使用的对象equal
为JComboBox