我目前正在开发一个基于文本的小型游戏,但我不断收到错误......
我不知道如何修复它,因为这是我第一次使用 JFrame
。问题是,
当我将 ButtonDemo
方法放入 ButtonDemo()
而不是 public static void ButtonDemo()
时,ButtonDemo 出现问题()
。但是,如果是 public static void ButtonDemo()
,则 jbtnW.addActionListener(this)
上会出现错误,表示我无法使用“this”,因为ButtonDemo()
是静态
。
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import game.Storylines.*;
public class Frame implements ActionListener{
VillageDrengr shops = new VillageDrengr();
static JLabel jlab;
static JFrame jfrm = new JFrame("A Game");
public static void ButtonDemo() {
jfrm.setLayout(new FlowLayout());
jfrm.setSize(500, 350);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtnW = new JButton("Equipment Shop");
JButton jbtnP = new JButton("Potion Shop");
jbtnW.addActionListener(this);
jbtnP.addActionListener(this);
jfrm.add(jbtnW);
jfrm.add(jbtnP);
jlab = new JLabel("Choose a Store.");
jfrm.add(jlab);
jfrm.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Equipment Shop"))
jlab.setText("You went in to the Equipment Shop.");
else
jlab.setText("You went in to the Potion Shop.");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ButtonDemo();
}
});
}
}
最佳答案
您收到错误
non-static variable
this
cannot be referenced from a non-static context`.
发生的情况是 this
引用了 ActionListener
,它不是静态
。
一个简单的修复方法是使 ButtonDemo
方法成为非静态的,并像这样从 main
调用该方法
public void ButtonDemo() {
....
public void run() {
new Frame().ButtonDemo();
}
您实例化Frame
类,并调用该方法。错误消失。
此外,您不应将类命名为 Frame
,因为已经有一个 AWT Frame
类。您可能会遇到问题。
此外,遵循 Java 命名约定,方法名称以小写字母开头,即 buttonDemo()
。在不看你的类名的情况下,我完全困惑地认为 ButtonDemo()
是类构造函数。
关于java - JFrame方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21215827/