簡體   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