简体   繁体   English

如何将ActionEvent添加到JButtons? 井字游戏

[英]How do I add ActionEvent to JButtons? TicTacToe

I'm new to coding and trying to create a simple tic-tac-toe game for class and I figured since I need to use GUI that i'd make the board a grid of buttons. 我是编码的新手,尝试为班级创建一个简单的井字游戏,因此我想起了这一点,因为我需要使用GUI来将板子做成一个按钮网格。 Unfortunately I am having issues getting the buttons to do anything. 不幸的是,我在让按钮执行任何操作时遇到问题。 I want to when someone clicks on it for it to become an X, and then the next person that clicks it becomes an O. Any help would be fantastic. 我想当某人单击它使其成为X,然后下一个单击它的人变为O。任何帮助都将非常棒。

import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.JOptionPane;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.layout.BorderPane;
import javafx.geometry.Pos;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import java.awt.font.*;
import javafx.animation.TranslateTransition;
import javafx.scene.layout.GridPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

public class ShadowT extends JFrame { 

   //creates 9 buttons
   private static JButton buttons[] = new JButton[9]; 
   //sets counter for amount of times a button has been clicked on
   public static int counter = 0;  
   public static String letter;

   public static void main(String[] args){
       //creates grid of 3x3
       int rows = 3;
       int cols = 3;
       ShadowT grid = new ShadowT(rows,cols);
       grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       grid.pack();
       grid.setVisible(true);
   }


   public ShadowT(int rows, int cols){
       //creates pane with grid and adds in the buttons 
       Container pane = getContentPane();
       pane.setLayout(new GridLayout(rows,cols));
       for(int i = 0; i < 9; i++){
           JButton button = new JButton(Integer.toString((i+1)));
           pane.add(button); 
       }
   }  
}

Each JButton needs an ActionListener (possibly the same), with a custom actionPerformed method. 每个JButton需要一个ActionListener (可能是相同的),以及一个自定义的actionPerformed方法。

For instance, for a JButton called button1, you could write 例如,对于一个名为button1的JButton,您可以编写

button1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        /* do some stuff when the button is clicked */
    }
});

See also How to Write an Action Listener in the Java Tutorial, and if you need it, How to add action listener that listens to multiple buttons here on SO. 另请参见Java教程中的如何编写动作侦听器 ,以及在需要时添加如何在SO上添加侦听多个按钮的动作侦听器

Here is an example: 这是一个例子:

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Grid extends JFrame implements ActionListener {
    private static JButton buttons[][];
    public static int counter = 0;

    public static void main(String[] args){
        Grid grid = new Grid(3, 3);
        grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        grid.pack();
        grid.setVisible(true);
    }

    public Grid(int rows, int cols) {
        Container pane = getContentPane();
        pane.setLayout(new GridLayout(rows, cols));
        buttons = new JButton[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                JButton button = new JButton(i + "," + j);

                button.addActionListener(this);
                pane.add(button);
                buttons[i][j] = button;
            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        Object o = e.getSource();
        if (o instanceof JButton) {
            JOptionPane.showMessageDialog(null, ((JButton)o).getText());
        }
    }
}

Here is an example of a bare bones Java GUI application - not perfect but to just to demo what you need to. 这是一个简单的Java GUI应用程序示例-并非完美,但仅用于演示您需要的内容。

You need to implements ActionListener and write actionPerformed() required when implementing ActionListener . 您需要实现ActionListener并编写实现ActionListener时所需的actionPerformed()

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class HandleActionEventsForJButton extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;

    public HandleActionEventsForJButton() {

        // set flow layout for the frame
        this.getContentPane().setLayout(new FlowLayout());

        JButton button1 = new JButton("Yes");
        JButton button2 = new JButton("No");

        //set action listeners for buttons
        button1.addActionListener(this);
        button2.addActionListener(this);

        //add buttons to the frame
        add(button1);
        add(button2);

    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        String action = ae.getActionCommand();
        if (action.equals("Yes")) {
            System.out.println("Yes Button pressed!");
        }
        else if (action.equals("No")) {
            System.out.println("No Button pressed!");
        }
    }

    private static void createAndShowGUI() {

  //Create and set up the window.

  JFrame frame = new HandleActionEventsForJButton();

  //Display the window.

  frame.pack();

  frame.setVisible(true);

  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {

  //Schedule a job for the event-dispatching thread:

  //creating and showing this application's GUI.

  javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

    createAndShowGUI(); 

}

  });
    }

}

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

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