Search code examples
javaswingjbuttonactionlistener

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


I'm trying to create a simple Tic-Tac-Toe program which uses both the terminal and a before game UI. I'm quite a noob at this, so please go easy. When I try to use ActionListener on a method I called, I get this error : Non static variable this cannot be referenced from a static context.

Here's my code:

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);




    }
}`

Thanks in Advance!


Solution

  • If I understand your question then here when you define your class

    class TicTacToe
    

    You also need to specify that TicTacToe implements the ActionListener interface (and to implement the one method it has);

    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.
        // ...
      }
    }
    

    Additionally, to use this in popupintroscreen it cannot be a static method. Finally, you need an instance of TicTacToe.