Java addActionListener(this) 创建错误

标签 java button compiler-errors

当我尝试按照我在网上找到的示例添加 ActionListener 时,它显示一条错误消息,指出“无法在静态上下文中使用它”。是否有任何解决方法,或者我应该完全尝试不同的方法?

        //Variable Declaration 
    Drink drink = new Drink(); 

    //Create type1Button 
    JButton type1Button = new JButton (drink.typeArray[1]); 
    type1Button.setMnemonic(KeyEvent.VK_1);
    type1Button.setActionCommand("drink1");

    //Create type2Button 
    JButton type2Button = new JButton (drink.typeArray[2]); 
    type2Button.setMnemonic(KeyEvent.VK_2); 
    type2Button.setActionCommand("drink2"); 

    //Create type3Button 
    JButton type3Button = new JButton (drink.typeArray[3]); 
    type3Button.setMnemonic(KeyEvent.VK_3); 
    type3Button.setActionCommand("drink3");

    //Create type4Button 
    JButton type4Button = new JButton (drink.typeArray[4]); 
    type4Button.setMnemonic(KeyEvent.VK_4);
    type4Button.setActionCommand("drink4");

    //Create type5Button 
    JButton type5Button = new JButton (drink.typeArray[5]); 
    type5Button.setMnemonic(KeyEvent.VK_5); 
    type5Button.setActionCommand("drink5"); 

    //Create Action Listeners 
    type1Button.addActionListener(this); 
    type2Button.addActionListener(this); 
    type3Button.addActionListener(this); 
    type4Button.addActionListener(this); 
    type5Button.addActionListener(this); 

编辑:
    public final void createListeners (JButton type1Button, JButton type2Button, JButton type3Button, JButton type4Button, JButton type5Button) {
    //Create Action Listeners 
    type1Button.addActionListener((ActionListener) this); 
    type2Button.addActionListener((ActionListener) this); 
    type3Button.addActionListener((ActionListener) this); 
    type4Button.addActionListener((ActionListener) this); 
    type5Button.addActionListener((ActionListener) this); 
}

现在的问题是当我尝试在静态 void main 中使用它时,它提示我无法对非静态方法进行静态引用,但我还能如何运行它?

最佳答案

使方法非静态。在静态上下文中没有“this”,这是没有意义的。您要么需要传入要使用的组件来代替“this”,要么需要使封闭方法成为非静态方法。

干杯

关于Java addActionListener(this) 创建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26982537/

相关文章:

java - Android ShoutCast 网络电台 FilenotFoundException

java - java中如何终止线程的执行?

ios - 如何在出现 searchController 时自动显示键盘

javascript - JS : Changing value in function doesn't work

c++ - 我可以告诉VC201 0 auto 增加预编译头分配(同/Zm)而不是获取c3859吗?

c++ - 无法将字符串流传递给构造函数

java - Weka 总是为不同的数据生成相同的集群

java - Java 7 中的椭圆曲线密码术实现

html - 有没有办法塑造 HTML 表单的提交按钮?

objective-c - 按下按钮时出现 SIGBAT 错误