javajframejbuttonjlabelactionevent

Java - Change label text on button press


I have edited question per requirements

So I want a label to change it's text when a button is pressed. But when I try to use setText() on the label when the button is clicked, it doesn't recognize it. Why is this?

public class SingleButton extends JPanel
    implements ActionListener {
    protected JButton b1;

    public SingleButton() {       
        b1 = new JButton("Axxxxxx"/*, leftButtonIcon*/);
        b1.setActionCommand("enableb1");
        b1.setEnabled(true);        
        b1.addActionListener(this);

        add(labelUpn);
        labelUpn.setText("UPN number here");
    }

    public void actionPerformed(ActionEvent e) {
        if ("enableb1".equals(e.getActionCommand())) {
            b1.setEnabled(false);
            labelUpn.setText("New Text");            
    }
}

Solution

  • A few problems with your code :

    . You never did call setText on the label inside your actionPerformed() method.

    . JLabel labelUpn is local to the constructor. Make it a class variable if you want to access it from within actionPerformed()

    With that in mind, you can tell which button was clicked by casting e.getSource() to JButton, you can then get its text (which I assume to be the "UPN") by calling getText() on it.

    public class ButtonDemo extends JPanel
    implements ActionListener {
        protected JButton b1, b2, b3, b4;
        protected JLabel labelUpn;
    
        public ButtonDemo() {
            //...
            labelUpn = new JLabel("UPN number here on button press");
            //...
        }
    
        public void actionPerformed(ActionEvent e) {
            //...
            JButton clicked = (JButton) e.getSource();
            labelUpn.setText(clicked.getText());
        }