Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!: ");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.stack.imgur.com/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();

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading