繁体   English   中英

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

[英]How do I use the ActionListener (this) command in Java

我正在尝试创建一个简单的井字游戏程序,该程序同时使用终端和游戏前UI。 我对此很菜鸟,所以请放轻松。 当我尝试在调用的方法上使用ActionListener时,出现以下错误: Non static variable this cannot be referenced from a static context.

这是我的代码:

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接口(并实现它具有的一种方法);

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实例。

嗯,代码的编写方式本质上是错误的。

您没有在此处定义任何ActionListener。 仅调用addActionListener(this)将没有任何作用。 您需要实现ActionListener。 替换行JButton.addActionListener(this); // you have to use the object of JButton - ie startgamebutton, not the JButton class here! addActionListener is not a static method of JButton JButton.addActionListener(this); // you have to use the object of JButton - ie startgamebutton, not the JButton class here! addActionListener is not a static method of JButton

与此(使用匿名内部类):

startgamebutton.addActionListener(new ActionListener() {
@Override
  public void actionPerformed(ActionEvent e) {
    System.out.println("In actionPerformed");
    // other code to handle the event when the button is clicked
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM