Question

Why will this actionlistener not display a pop up box when you click the button "Rock"? Solutions?

ClickListener cl1 = new ClickListener();    
JPanel panel1 = new JPanel();
    JButton Rock = new JButton("Rock");
    Rock.addActionListener(cl1);
    panel1.add(Rock);
    this.add(panel1);
    this.setVisible(true);
}
private class ClickListener implements ActionListener{

    public void actionPerformed(ActionEvent e){
        if(e.getSource() == "Rock"){
            int AI = new Random().nextInt(3) + 1;
            JOptionPane.showMessageDialog(null, "I have been clicked!");
        }
    }
}

}

Was it helpful?

Solution

Use

if("Rock".equals(e.getActionCommand()){

As long as you don't explicitly set the action command for the button, e.getActionCommand() will return the string text you pass to it's constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top