While I don't really like the if-else approach you're using, it should work just fine. I agree with rrirower's suggestion that you should look at using a data model instead. Especially if you get a lot of choices, since the code turns messy quite fast.
The problem with your code is that you run into NullPointerException
when rebuilding the combobox items. The reason for this is that G.actionPerformed()
is called when you remove/add items. After you have removed all items (before you start adding new ones), G.getSelectedItem()
will return null.
If you code a little bit more defensively, then it works as expected:
proc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selectedItem = proc.getSelectedItem();
if ("Choice1".equals(selectedItem)) {
setGyd(Option1);
}
if ("Choice2".equals(selectedItem)) {
setGyd(Option2);
}
}
});
G.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
Object selectedItem = G.getSelectedItem();
if ("A1".equals(selectedItem)) {
setLaikas(Option3);
}
if ("A2".equals(selectedItem)) {
setLaikas(Option4);
}
if ("A3".equals(selectedItem)) {
setLaikas(Option5);
}
}
});//JComboBox
Instead of checking for null's, I just flipped the equals and skipped the unnecessary toString()
(they are already strings, that's what you put in there).
Another thing, a pet peeve of mine, please follow the normal java code convention for all your class, field and method names. You're almost there, but Option1
etc. should start with lowercase. G
should probably have a more descriptive name, as well as start with lowercase.
Finally, I didn't understand why you both create a JFrame
in the constructor and extend JFrame
in your class. You should choose one or the other.