I have some code which is used to change a txtArea in a program when certain buttons are clicked then an ActionListener performs an action.
reset.addActionListener(new ButtonsAction());
hint.addActionListener(new ButtonsAction());
solve.addActionListener(new ButtonsAction());
newPuzzle.addActionListener(new ButtonsAction());
public class ButtonsAction implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {//implements actionPerformed
Object button=e.getSource();
if(button.equals(hint))
{
jtxtar.setText("Hint button clicked!");
}
else if(button.equals(reset))
{
jtxtar.setText("Reset button clicked!");
}
else if(button.equals(solve))
{
jtxtar.setText("Solve button clicked!");
}
else
{
jtxtar.setText("New Puzzle button clicked!");
}
}
}
However I also have a JComboBox which when selecting one of it's three option should also clear the field, but then add a message like, "Difficulty changed to ...." .
Looking up how JComboBox works, I believe I need to use an ItemListener rather than ActionListener. Looking at the tutorials has not helped me glean much from this however. But I did find something that said I needed a whole new Listener class to implement it.
diffBox.addItemListener(new CBoxAction());
public class CBoxAction implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED) {
diffBox.getSelectedItem();
jtxtar.setText();
}
The problem here is I am not sure what I should have it do to tell the jtxtar clear and tell the user they changed to that difficulty.
After re-looking at Oracle's JComboBox Demo, I got my answer. I add this to my else statements, appending the last statement as else if, then adding the code that sets the jtxtar to tell the use their difficulty. No need for another class as it uses the ActionListener also.
And now when you click the ComboBox and choose a new difficulty, the jtxtar clears and says that difficulty.