我目前正在開發一個小型的基於文本的遊戲,並且我不斷收到錯誤... 我不知道如何解決它,因爲它第一次使用JFrame
。問題是,當我將ButtonDemo
方法轉換爲ButtonDemo()
而不是public static void ButtonDemo()
時, 存在ButtonDemo()
問題。但是,如果是public static void ButtonDemo()
,則在jbtnW.addActionListener(this)
上會出現錯誤,並說我不能使用「this」,因爲ButtonDemo()
是static
。JFrame方法概要
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();
}
});
}
}
那麼,究竟**是** ButtonDemo()方法的問題?你只會說「有問題」......錯誤是什麼?你可以粘貼堆棧跟蹤嗎? –
也許你想要一個構造函數而不是方法,然後在'main'中執行'new ButtonDemo()'。構造函數'public ButtonDemo(){}' –