我目前正在开发一个基于文本的小型游戏,并且一直出现错误...我不知道如何修复它,因为这是我第一次使用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();
}
});
}
}