Java – How to get the text of a button in Java

java

class Test extends JPanel implements MouseListener
{
    private JButton b1, b2, b3, b4;

    public Test()
    {
        setLayout (new GridLayout (2, 3));

        b1 = new JButton ("Button 1");
        b2 = new JButton ("Button 2");

        add (b1);
        add (b2);
    }

    public void mousePressed (MouseEvent event)
    {
        if (event.getText() == b1.getText())
        {
        }
    }
}

I was wondering if there was a method within the MouseListener or JPanel class that allows me to get the text of a button that is clicked. Thanks

Best Solution

You should try looking at ActionListener and implement it. Those Actions are fired, whenever you click a button, this is how you should work:

class Test extends JPanel implements ActionListener {
...
   public Test() {
        super();
        ...
        b1 = new JButton("Button 1");
        ...
        add(b1);
        ...
        b1.addActionListener(this);
        ...
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        System.out.println(((JButton) event.getSource()).getText());
        if (event.getSource() == b1) {
            // do sth
        } else if (event.getSource() == b2) {
            // do sth else
        }
    }
}

Then write a main method and add a new instance of Test panel to a JFrame and see how it works.

Tutorial can be found on the following website: http://docs.oracle.com/javase/tutorial/uiswing/components/button.html