【发布时间】:2014-08-25 14:23:42
【问题描述】:
我有这个代码:
private static void inputGUI() {
inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inputFrame.setTitle("The INPUT");
panel.add(printButton);
printButton.setBounds(135,560,120,30);
inputFrame.setLayout(null);
inputFrame.add(panel);
panel.setBounds(1000,100,366,768-100);
//ActionListeners!!!
printButton.addActionListener(this);
inputFrame.setSize(1366,768);
inputFrame.setVisible(true);
}
我想在名为
的 JButton 中添加一个动作监听器printButton
我也有一个 JFrame
inputFrame
这在我的 Main
public static void main (String[] args) {
inputGUI();
}
但我不断收到此错误:
error: non-static variable this cannot be referenced from a static context
我该怎么做?如果你们能在不使用匿名内部课程的情况下帮助我,那就太好了。(我的老师还没有教我们那节课)。谢谢!
【问题讨论】:
-
我们需要看到整个班级来诊断您的问题。理想情况下,您应该先从代码中消除不必要的细节,然后再给出一个简短的示例让我们重现问题。
-
你可以让你的方法是非静态的。
-
您可以将 printButton 和 inputFrame 设为静态(更简单),或者将您的静态方法转换为非静态方法,初始化您的类的实例,然后调用您的方法。
标签: java swing constructor static jframe