假设我有一个JComboBox,其中包含向量中的元素......
public class Shade(){
//code for creating panels etc and other components/containers
JCheckBox primary = new JCheckBox("Primary", false);
Vector<String> colours = new Vector<String>();
}
public Shade(){
//setTitle, look&feel, defaultCloseOperation, Layouts etc etc...
colours.add(0, "Purple);
colours.add(1, "Red");
colours.add(2, "Blue");
colours.add(3, "Magenta");
JComboBox<String> colourSelector = new JComboBox<String>(colours);
}
如果选择了JCheckBox primary,我想从JComboBox中“隐藏”颜色purple和magneta,一旦取消选择主JCheckBox,我想揭示隐藏的元素,以便原始列表相关。
我试过这样做......
public class eventHandler implements itemListener(){
Shade refObj;
public eventHandler(Shade rinseFM){
refObj = rinseFM;
}
#Overriding abstract implemented method...
public void itemStateChanged(ItemEvent event){
if(refObj.primary.isSelected() == true){
refObj.colours.hide(// index of colours required to hide))
}
}
}
hide方法实际上并不存在,有什么类似的东西。
答案 0 :(得分:2)
试试这个:
private JFrame frame = new JFrame("JComboExample");
private JCheckBox primary = new JCheckBox("Primary");
private JComboBox<String> colorSelector;
private String[] colorsToHide = { "Purple", "Magenta" };
public JComboExample() {
SwingUtilities.invokeLater(() -> {
setupFrame();
setupCheckbox();
initJComboBox("Purple", "Red", "Blue", "Magenta");
frame.add(primary, BorderLayout.NORTH);
frame.add(colorSelector, BorderLayout.CENTER);
});
}
private void setupFrame() {
frame.setSize(300, 100);
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(3);
frame.setLayout(new BorderLayout());
}
private void setupCheckbox() {
primary.addActionListener(event -> {
if(primary.isSelected()) {
for(String color: colorsToHide) {
colorSelector.removeItem(color);
}
} else {
for(String color: colorsToHide) {
colorSelector.addItem(color);
}
}
});
}
private void initJComboBox(String... colors) {
colorSelector = new JComboBox<String>(colors);
}
public void setVisbility(boolean visibility) {
frame.setVisible(visibility);
}
public static void main(String[] args) {
JComboExample example = new JComboExample();
example.setVisbility(true);
}
当单击复选框时,此类实现回调(添加ActionListener)。在回调中,当复选框被激活时,我们只需删除数组colorsToHide
中的颜色。如果未激活该复选框,我们会将其添加回来。
旁注:
在Java中,您不应该为此目的使用向量。矢量在很大程度上被认为是过时的。请参阅此帖子:Why is Java Vector class considered obsolete or deprecated?
您还应该在EDT上创建所有GUI /处理所有GUI状态更改。 Swing不是线程安全的,虽然在大多数情况下它可能看起来不需要,但最好在处理GUI之前调用SwingUtilities.invokeLater
或SwingUtilities.invokeAndWait
。