Search code examples
javaswingjbutton

Swing JButton not working on actionPerformed method


I have this beginner's project. This time I started from the basics.

Source code: https://github.com/kontext66/GuwiPos/blob/main/GuwiPos

The button is working fine with the lambda approach: buttonBasket.addActionListener(e -> System.out.println("Item Added to Basket!: ");

But when I try to use actionPerformed here to print out the content of the txtGroup, it does not show anything.

This is the Button and TextField [1]: https://i.sstatic.net/ADqVp.png

Button:

JButton buttonBasket = new JButton();
buttonBasket.setBounds(0,0,300,50);
buttonBasket.setText("Add to Basket");
buttonBasket.setFocusable(false);
buttonBasket.setBorder(BorderFactory.createEtchedBorder());   
buttonBasket.addActionListener(this);

Text Field:

JTextField txtGroup = new JTextField();
txtGroup.setBounds(130,35,150,40);

actionPerformed:

@Override
public void actionPerformed(ActionEvent e ){
    if(e.getSource()==buttonBasket){            
        System.out.println("Added Item to Basket: "+txtGroup.getText());
    }


Solution

  • Digging through your code, I see that you declare an instance variable buttonBasket and then declare a local variable buttonBasket in the constructor. When you call buttonBasket.addActionListener(this), you are really adding the listener to the local buttonBasket while the global buttonBasket is null.

    public class GuwiPos extends JFrame implements ActionListener{
      
            JButton buttonBasket;
            
             GuwiPos(){
                 JButton buttonBasket = new JButton();  // <=== local variable buttonBasket
                 buttonBasket.addActionListener(this);
             }
             
            public void actionPerformed(ActionEvent e ){
                if(e.getSource()==buttonBasket){    //<== buttonBasket is null         
                   System.out.println("Added Item to Basket: "+txtGroup.getText());
               }
            }
            
    }
    

    The solution is to change line:

    JButton buttonBasket = new JButton();

    to

    buttonBasket = new JButton();