gpt4 book ai didi

java - 无法从静态主函数内部调用非静态构造函数

转载 作者:行者123 更新时间:2023-12-02 10:42:01 24 4
gpt4 key购买 nike

public class Main {
private JLabel lb = new JLabel();
private JButton btn = new JButton();

public class events extends JFrame{
public events(){
setLayout(new FlowLayout());

btn = new JButton("Click for text");
lb = new JLabel();

add(btn);
add(lb);

event e = new event();
btn.addActionListener(e);

}
public static stConst() {

}
}

public class event implements ActionListener{
public void actionPerformed(ActionEvent e) {
lb.setText("Now there is text here.");
}
}

public static void main(String[] args) {
events gui = new events();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 300);
gui.setVisible(true);
}
}

好吧,在您对我的命名约定大喊大叫之前,请允许我说我知道我的变量名有多糟。我一直在尝试弄清java.swing事件的处理方式,最终找到了一个我认为可能有用的示例程序,但随后出现了错误“无法从静态上下文引用非静态变量”。它在我调用构造函数的底部的行上给了我错误,所以我认为该错误与构造函数中使用的“this”对象有关,或者可能由于某种原因不允许我调用我的非静态构造函数从我的静态main函数内部。我该如何解决?

最佳答案

因为事件是非静态内部类,所以它必须需要父类的引用才能初始化。

选项1:

您可以在静态方法中使用以下语句简单地调用内部类构造函数:

events gui = new Main().new events();

选项2:

创建一个非静态函数(如init),然后从该函数创建事件实例。从静态函数创建父类的实例,然后调用此非静态函数:
public static void main(String[] args) {
Main main = new Main();
main.init();
}

public void init() {
events gui = new events();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 300);
gui.setVisible(true);

}

输出:

enter image description here

关于java - 无法从静态主函数内部调用非静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617774/

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