有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java需要帮助理解特定getter如何影响我的程序

我对编码非常陌生(2个月),我试图用java实现Tic-Tac-Toe。我有点过头了,但我还是用swing创造了它。我的主要问题是button1类。我本来打算使用getText()方法,但最终不需要它,至少我是这么想的。我试着删除它,但事实证明,没有它,我的TictaToe按钮无法切换字母。编译器告诉我它重写了AbstractButtongetText()方法,但我不明白为什么这应该很重要,因为我从未真正使用过它。我想这可能是一个范围问题,因为它被覆盖了,但我不确定。我试图使用text变量用setText()更新按钮,但这似乎不像我认为的那样有效。我也不明白为什么3×3的网格布局在大多数情况下似乎工作正常,但有时添加的按钮数量是错误的

总之,这个程序(大部分)是有效的,但我不完全理解button1类是如何工作的

蒂克塔克托。爪哇

import java.awt.*;
import java.util.*;
import javax.swing.*;

public class TicTacToe extends JFrame {

public static void main(String[] args) {
    JFrame window = new JFrame("Tic-Tac-Toe");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
    window.setSize(600, 600);
    window.setLayout(new GridLayout(3, 3));

    ArrayList<button1> buttonArrayList = new ArrayList<>(9);

    for (int i = 0; i < 9; i++) {
        button1 newbutton = new button1();
        buttonArrayList.add(newbutton);
        window.add(buttonArrayList.get(i));
    }
}
}

按钮1。爪哇

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;

public class button1 extends JButton {
int value = 0;
String text = "";

public button1() {

    class ButtonAction extends AbstractAction {
        public ButtonAction() {}
        @Override
        public void actionPerformed(ActionEvent Switcher) {
            System.out.println(text + " " + value);
            value++;//value is a relic from earlier attempts that i just felt like keeping.
            if (text.equals("O")) {
                text = "X";
            } else if (text.equals("X")) {
                text = "";
            } else if (text.equals("")) {
                text = "O";
            }
        }
    }
    this.setAction(new ButtonAction());
    this.setText(text);
    this.setFont(new Font("Arial",Font.PLAIN,120));
}

public String getText()// <----culprit
{
    return text;
}
}

共 (2) 个答案

  1. # 1 楼答案

    您尝试过的是通过扩展AbstractActionnameebutton1来创建一个定制的Button类及其EventHandler,正如我们在您的问题中看到的那样

    您已经根据自己的定义覆盖了actionPerformed(ActionEvent Switcher)方法,该方法实际上属于类AbstractAction(每个按钮的操作事件应该执行什么操作)

     class ButtonAction extends AbstractAction {
            public ButtonAction() {}
            @Override
            public void actionPerformed(ActionEvent Switcher) { // Your Definition For actionPerformed..
                System.out.println(text + " " + value);
                value++;//value is a relic from earlier attempts that i just felt like keeping.
                if (text.equals("O")) {
                    text = "X";
                } else if (text.equals("X")) {
                    text = "";
                } else if (text.equals("")) {
                    text = "O";
                }
            }
        }
        this.setAction(new ButtonAction()); // add ActionListener to each Button.
        this.setText(text); // Setting Text to each Button
        this.setFont(new Font("Arial",Font.PLAIN,120)); //add Font to each Button.
    }
    

    现在在这段代码中

    ArrayList buttonArrayList=新建ArrayList<>;();

    for (int i = 0; i < 9; i++) {
        button1 newbutton = new button1(); // Creating 9  new buttons.
        buttonArrayList.add(newbutton); // add each button into the ArrayList.
        window.add(buttonArrayList.get(i)); // each Button to the the AWT Window.
    }
    

    上面的代码将生成9按钮,并将其添加到AWT Window中。每个button都有actionPerformed()方法,其中包含overrided定义

    现在,每个按钮都将按照actionPerformed()方法的定义执行操作

    谢谢

  2. # 2 楼答案

    JButton类有一个为其定义的方法,包括setText()(它将设置按钮上显示的文本)和getText()(它将返回按钮上显示的当前文本)

    您创建了一个类按钮1(注意:类应该以大写字母开头)

    您向button1类添加了一个动作,这意味着当该动作被激活时,会发生一些事情。注意,在actionPerformed方法中,应该调用setText(text)来更新显示的值

    您还定义了一个getText()方法,该方法覆盖JButton中定义的getText()方法。如果这是一个有意识的设计决策,那么这种方法很好。实际上,我认为应该从button1类中删除getText()方法,并允许标准JButton类处理更新。现在,您正试图将实例变量text与该值保持一致,但该实例变量可能与按钮的实际显示值不一致(请考虑另一个类调用按钮上的.setText()

    编辑:确实this指的是按钮操作中的JButton不可用。然而,动作本身包含被按下的按钮

        @Override
        public void actionPerformed(ActionEvent e)
        {
            JButton btn = (JButton)e.getSource();
    
            // if desired, String cur = btn.getText() may be called to find the
            //  current setting; get and process if needed
            btn.setText(WHAT_EVER_TEXT);
        }
    

    但是,除非是处理当前文本的特定要求(允许选择O到X到空白),否则我会实现一些跟踪当前回合的功能。这段代码是我正在试验的东西,它有好的方面,也有坏的方面(因为它是说明性的):

    static class TurnController
    {
        // whose turn it is; start with X
        private Player whoseTurn = Player.X;
    
        // the instance variable
        private static final TurnController instance = new TurnController();
    
    
        private TurnController()
        {
        }
    
        public static Player currentTurn()
        {
            return instance.whoseTurn;
        }
    
        public static Player nextTurn()
        {
            switch (instance.whoseTurn) {
            case X:
                instance.whoseTurn = Player.O;
                break;
    
            case O:
                instance.whoseTurn = Player.X;
                break;
            }
    
            return instance.whoseTurn;
        }
    
        public static String getMarkerAndAdvance()
        {
            String marker = currentTurn().toString();
    
            nextTurn();
    
            return marker;
        }
    
        enum Player
        {
            X,
            O,
            ;
        }
    }
    

    使用此TurnController,actionPerformed变为:

        @Override
        public void actionPerformed(ActionEvent e)
        {
            JButton btn = (JButton)e.getSource();
    
            btn.setText(TurnController.getMarkerAndAdvance());
        }
    

    Button1类可能删除了String text实例变量