我正在尝试创建一个简单的 Tic-Tac-Toe 程序,该程序同时使用终端和游戏前 UI。我对此很菜鸟,所以请放轻松。当我尝试在我调用的方法上使用 ActionListener 时,出现此错误:非静态变量不能从静态上下文中引用。
这是我的代码:
import java.util.Random ;
import java.util.Scanner ;
import javax.swing.JOptionPane ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import java.util.InputMismatchException ;
import java.awt.BorderLayout ;
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.JTextArea ;
import javax.swing.JButton ;
import javax.swing.JRadioButton ;
class TicTacToe
{
public int inp1 ;
public int inp2 ;
public static void main(String []args)
{
popupintroscreen();
}
public static void popupintroscreen()
{
JTextArea introtext = new JTextArea("Hello and welcome to TicTacToe v.1.0");
introtext.setEditable(false);
introtext.setLineWrap(true);
introtext.setWrapStyleWord(true);
JButton startgamebutton = new JButton("Start Game");
JButton.addActionListener(this);
JPanel content = new JPanel(new BorderLayout());
content.add(introtext);
content.add(startgamebutton);
JFrame introscreen = new JFrame("Tic Tac Toe");
introscreen.setSize(400,400);
introscreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
introscreen.setLocationRelativeTo(null);
introscreen.add(content);
introscreen.setVisible(true);
}
}`
提前致谢!
最佳答案
如果我理解你的问题,那么当你定义你的类时
class TicTacToe
您还需要指定 TicTacToe
实现 ActionListener
接口(interface)(并实现它所具有的一种方法);
class TicTacToe implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("TicTacToe.actionPerformed: " + e);
}
public static void main(String []args)
{
new TicTacToe().popupintroscreen();
}
public void popupintroscreen() { // <-- not static.
// ...
}
}
此外,要在 popupintroscreen
中使用 this
,它不能是静态方法。最后,您需要一个 TicTacToe
实例。
关于java - 如何在 Java 中使用 ActionListener (this) 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24760005/