Reputation: 601
I have a combo box as you can see in the code that takes the values from a table. So after I click ok the values of the table change. How can I see these new values to the compobox without to close and open the jframe ? I made a lot of study today about java.awt.EventQueue.invokeLater and othe staff but I can not make it work, I am new to java and to programing general. So here is the code:
public class Compo extends JFrame implements ActionListener
{//start of class Compo
//start of variables
private JComboBox<String> CompoBox;
private String array[];
private JButton okButton;
private JPanel panel;
//end of variables
public Compo ()
{//start of Compo method
super("Example");
panel=new JPanel(null);
//table = new String[3];
array= new String[3];
array[0]="alpha";
array[1]="beta";
array[2]="charlie";
CompoBox= new JComboBox<>(array);
CompoBox.setBounds(50, 70, 100, 20);
panel.add(CompoBox);
okButton=new JButton("ok");
okButton.setBounds(50, 120, 70, 30);
okButton.setActionCommand("ok");
okButton.addActionListener(this);
panel.add(okButton);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 200);
setVisible(true);
}//end of compo method
@Override
public void actionPerformed(ActionEvent event)
{//start of actionperformed
String testString=event.getActionCommand();
if (testString.equals("ok"))
{//start of if
for (int i = 0; i < array.length; i++)
{
String sample= array[i];
array[i]=sample+"aa";
}
}//end of if
}//end of aciton performed
}//end of class Compo
Upvotes: 1
Views: 9016
Reputation: 88707
You can either use the addItem(...)
and removeItem(...)
methods on the combobox directly or provide your own ComboBoxModel
and change the data in that model.
Although I'd generally like to use the latter option (i.e. my own model), for your skill level I'd suggest starting with the add/remove methods first.
Later you might want to work on the default model (which is of class DefaultComboBoxModel
and implements MutableComboBoxModel
). Keep in mind though, that you'd need a cast and be sure you get a model of the correct type in this case.
Upvotes: 2
Reputation: 6825
this should be the answer you are looking for, hope you'll accept it:
if (testString.equals("ok")) {
CompoBox.removeAllItems();
for (int i = 0; i < array.length; i++) {
String sample = array[i];
CompoBox.addItem(sample + "aa");
}
}
btw. the generic comqo-pox is done like this:
CompoBox = new JComboBox<String>(array);
Upvotes: 6