I'm trying populate a JComboBox, whenever a button is clicked in a different frame. In the other frame, there is a text field where a person enters a name for example and a submit button, that is all. Every time the submit button is clicked, I want to populate the JComboBox. Here is the code to demonstrate what I mean. The code works, with static variables, something I'm wanting to avoid if possible.
public class Frame1Panel extends JPanel{
private static MyComboBox comboBox;
private JButton addItemsButton, exitButton;
public Frame1Panel() {
comboBox = new MyComboBox();
exitButton = new JButton("exit");
addItemsButton = new JButton("Add Items");
Dimension dim = addItemsButton.getPreferredSize();
addItemsButton.setPreferredSize(dim);
setupLayout();
exitButton.setPreferredSize(dim);
addItemsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addItemsButton) {
Frame2 frame2 = Frame2.getInstance();
frame2.setVisible(true);
}
}
});
//This is what I'm trying to avoid. This works of course
public static MyComboBox getComboBox() {
return comboBox;
}
}
}
If you notice, I just use Frame1Panel and call the getComboBox method and of course the addItem method and it works as expected. Again is there way where I can avoid using static?
public class Frame2Panel extends JPanel {
private JTextField nameTextField;
private JLabel nameLabel;
private JButton submitButton;
public Frame2Panel() {
setLayout(new GridBagLayout());
nameTextField = new JTextField(10);
nameLabel = new JLabel("Name: ");
submitButton = new JButton("Submit");
setupLayout();
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String name = nameTextField.getText();
Frame1Panel.getComboBox().addItem(name);
}
});
}
}
If anyone is wondering as to why I have a separate MyComboBox class, that is because I incorporate the DefaultComboBoxModel so Eclipse doesn't yell at me, when I use the window design editor, it isn't necessary to the question to include it, You can assume MyComboBox doesn't exist and just think it is JComboBox instead.