【问题标题】:Swing JButton not working on actionPerformed methodSwing JButton 不适用于 actionPerformed 方法
【发布时间】:2022-01-31 03:02:08
【问题描述】:

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

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

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

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

这是 Button 和 TextField [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());
    }

【问题讨论】:

标签: java swing jbutton


【解决方案1】:

挖掘你的代码,我看到你声明了一个实例变量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();

【讨论】:

  • 所以我尝试从局部变量中删除JButton buttonBasket = new JButton(); 并保留按钮的属性我收到此错误消息Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.swing.JButton.setBounds(int, int, int, int)" because "this.buttonBasket" is null at GuwiPos.&lt;init&gt;(GuwiPos.java:79) at Main.main(Main.java:24)
  • 您仍然需要创建一个按钮。而不是JButton buttonBasket = new JButton();,应该是buttonBasket = new JButton();
  • 现在可以了 我还编辑了 textField 部分。谢谢你,先生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
相关资源
最近更新 更多