gpt4 book ai didi

Java addActionListener(this) 创建错误

转载 作者:行者123 更新时间:2023-12-02 11:03:36 25 4
gpt4 key购买 nike

当我尝试按照我在网上找到的示例添加 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com