Swing JButton 不适用于 actionPerformed 方法

Swing JButton not working on actionPerformed method

我有这个初学者项目。这次我从基础开始。

源代码:https://github.com/kontext66/GuwiPos/blob/main/GuwiPos

按钮在 lambda 方法下运行良好: buttonBasket.addActionListener(e -> System.out.println("Item Added to Basket!: ");

但是当我尝试在这里使用actionPerformed打印出txtGroup的内容时,它没有显示任何内容。

这是按钮和文本字段 [1]: https://i.stack.imgur.com/ADqVp.png

按钮:

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);

文本字段:

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());
    }

仔细研究您的代码,我发现您声明了一个实例变量 buttonBasket,然后在构造函数中声明了一个局部变量 buttonBasket。当你调用 buttonBasket.addActionListener(this) 时,你实际上是在将监听器添加到本地 buttonBasket 而全局 buttonBasketnull.

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());
           }
        }
        
}

解决方法是换行:

JButton buttonBasket = new JButton();

buttonBasket = new JButton();