0

I have few JFrames. Using one of them (it contains textBox) I want to transfer inputed data to the variable in another class. This variable is used to build JComboBox choose list. I try to transfer inputed data via JButton, but in the end nothing is transferred and JComboBox stays empty. Do I need to somehow refresh JComboBox or something? My code:

...
DataBase toTable = new DataBase();
...

button.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent click) {

                toTable.data[0] = textField.getText();

                }           
});

Variable from DataBase class:

....
String data[] = {"","","","",""};
....

And the Main Class (it contains JComboBox):

...
DataBase data0 = new DataBase();
final JComboBox list0 = new JComboBox(data0.data);
        list0.setBounds(10, 61, 110, 22);
        contentPane.add(list0);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3019431
  • 11
  • 1
  • 1
  • 4

1 Answers1

1

That's correct. The JComboBox doesn't notice that you updated the array. You will need to use the addItem or setModel method of JComboBox.

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent click) {
        toTable.data[0] = textField.getText();
        list0.setModel(new DefaultComboBoxModel(toTable.data));
    }           
});

Of course, this code won't run unless you can reference list0 in the same scope as your button. I would recommend putting button and list0 in the same class, if possible.

aebabis
  • 3,657
  • 3
  • 22
  • 40
  • Both items don't necessarily must be in the same class, you can have a getter for each one. Anyway, I would try and implement a solution more like the Gamma book Subject-Observer pattern, in order to decouple all that objects (what happens if you have 3 or 4 objects with that schema?) – Jorge_B Jan 13 '14 at 23:49
  • @Jorge_B I agree that the Observer-Observable pattern is very useful, but without seeing more of his code, we don't know whether or not that would be overkill. Sometimes its better to put all the coupling in the same class that builds the GUI. – aebabis Jan 13 '14 at 23:58