java - 如何在 Java 中使用 ActionListener (this) 命令

标签 java swing jbutton actionlistener

我正在尝试创建一个简单的 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/

相关文章:

java - repaint() 不在线程中工作

java - 无功能的 JButton

java - CursorIndexOutOfBoundsException : Index -1 requested,,大小为 163

java - 使用 Selenium WebDriver 测试元素是否存在?

java - Spring 4 MVC 和 Websockets - 没有合适的默认 RequestUpgradeStrategy

java - 使用 AwesomeFont 中的自定义字体和 Java Swing 中的 unicode 字符向 JButton 添加图标?

java - 如何使 JButton 名称的一部分着色?

Java 核心还是 Java EE?

java - 如何在 `Java Swing` 中获取鼠标悬停事件

java - 如何以动态大小居中 JPanel