0

我目前正在开发一个基于文本的小型游戏,并且一直出现错误...我不知道如何修复它,因为这是我第一次使用JFrame. 问题是,当我将ButtonDemo方法变成ButtonDemo(), notpublic static void ButtonDemo()时,ButtonDemo(). 但是,如果是public static void ButtonDemo(),就会出现错误jbtnW.addActionListener(this),说我不能使用“this”,因为ButtonDemo()is static

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();
            }
        });
    }

}
4

1 回答 1

1

你收到一个错误

this不能从非静态上下文中引用非静态变量。

正在发生的事情this是引用ActionListenerwhich is not static

一个简单的解决方法是使该ButtonDemo方法非静态,并main像这样调用该方法

        public void ButtonDemo() {
        ....

        public void run() {
           new Frame().ButtonDemo();
        }

您实例化Frame该类,并调用该方法。错误消失。

此外,您不应该为您的班级命名Frame,因为已经有一个 AWTFrame班级。你可能会遇到问题。

此外,遵循 Java 命名约定,方法名称以小写字母开头,即buttonDemo(). 不看你的类名,我就完全糊涂了,以为ButtonDemo()是类构造函数。

于 2014-01-19T11:16:52.767 回答