Search code examples
javaswinguser-interfacebuttonactionlistener

ActionListener on JButton


Is it possible to add different ActionListener on different Buttons? I have the problems that I have a JComboBox to set the difficulty level of my game and a button which should start the game.

So the question is how can i make it that I am able to select the difficulty level and then start the game by clicking on another button

enter image description here


Solution

  • You don't need a "different ActionListener", you just need to obtain the result from the JComboBox inside the JButton's ActionListener, and use this result to determine what direction the program should go.

    myButton.addActionListener(e -> {
        // get combo selection -- assuming that it holds Strings. Better if it held enums though
        String selection = (String) myCombo.getSelectedItem();
        
        // here use if blocks or a switch statement decide what to do
        if (selection.equals(foo)) {
            //....
        } else if (selection.equals(bar)) {
            //...
        } else if.....
    });
    

    I wouldn't even add a listener to the JComboBox, since the action will only start when the user selects the button.