简体   繁体   English

JComboBoxes的ArrayList导致JComboBoxes彼此锁定

[英]ArrayList of JComboBoxes causing JComboBoxes to lock to each other

This is the problem I'm having: I have an ArrayList of 5 JComboBox 's. 这是我遇到的问题:我有一个5 JComboBoxArrayList These JComboBox 's each contain the same five options: "1", "2", "3", "4", and "5" . 这些JComboBox都包含相同的五个选项: "1", "2", "3", "4", and "5" I then add the ArrayList of JComboBox 's to a JFrame via a for loop. 然后,我通过for循环将JComboBoxArrayList JComboBoxJFrame However, for some odd reason, whenever I select an option in one of the JComboBox 's, the rest of the JComboBox 's also select that reason. 但是,出于某种奇怪的原因,每当我在JComboBox的其中一个中选择一个选项时,其余的JComboBox也会选择该原因。 This first screenshot is of the JFrame in its state when first executed : 第一个屏幕快照是 JFrame 在首次执行时的状态 screenshot1

This is a screenshot of the user selecting another menu item: 这是用户选择另一个菜单项的屏幕截图: screenshot2

And this third screenshot shows that ALL the JComboBox 's changed to the selected input. 第三张屏幕截图显示,所有JComboBox更改为选定的输入。 screenshot3

This is my code: 这是我的代码:

class Foo {
    JFrame frame = new JFrame("Add person(s)");
    ArrayList<JComboBox> comboArray = new ArrayList<JComboBox>();

    String[] floors = {"1", "2", "3", "4", "5"};
    DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>(floors);

public void go() {
    for (int x = 0; x < 5; x++) {
        comboArray.add(new JComboBox<String>(model)); //Adds numbers 1-5 to a new JComboBox, and the JComboBox is then added to comboArray
        frame.add(comboArray.get(x)); //Adds each JComboBox to the frame
    }
    frame.setResizable(false);   
    ...
    frame.setVisible(true);
}

public static void main (String [] args) {
    go();
}

}
comboArray.add(new JComboBox<String>(model)); 

You are adding the same ComboBoxModel to each combo box. 您正在向每个组合框添加相同的ComboBoxModel

You need to create a separate model for each combo box. 您需要为每个组合框创建一个单独的模型。

So the code inside the loop should be: 因此,循环内的代码应为:

DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>(floors);
comboArray.add(new JComboBox<String>(model)); 

Now each combo box contains a separate model, but each model contains the same values. 现在,每个组合框都包含一个单独的模型,但是每个模型都包含相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM