【问题标题】:How to manipulate variables in a class, from a different class?如何操作来自不同类的类中的变量?
【发布时间】:2014-01-04 13:29:32
【问题描述】:

使用 Java 开发一个简单的井字游戏。

我有一个名为GameHelpers 的类。这个类应该包含对游戏有用的方法。游戏发生在另一个班级。

GameHelpers 中的方法是ResetGame()。此方法应该将所有 9 个按钮(井字游戏板)上的文本设置为空白,再次将它们设置为启用,并将变量设置为 1。

这是它的代码:

public class GameHelpers {

    public void resetGame(){
        for(int i=0;i<3;i++){
            for(int j=0;j<3;j++){
                buttons[i][j].setEnabled(true);
                buttons[i][j].setText("");
                count = 1;
            }
        }
    }

}

buttons[] 是游戏主类TicTacToe 中的一个 JButton 数组。

这个方法以前在游戏的主类TicTacToe 中。但是现在它在不同的类中,它无法到达TicTacToe 类中的按钮并对其进行操作。

我在TicTacToe 中创建了get 和set 方法,但是如何从GameHelpers 激活它们?

如何使GameHelpers 中的方法起作用?

【问题讨论】:

    标签: java class


    【解决方案1】:

    您可以通过 ActionEvent 的getSource() 方法获取被推送的源按钮。

    例如:

    public void actionPerformed(ActionEvenet e){
         JButton sourceBtn = (JButton) e.getSource();
         String text = sourceBtn.getText().trim(); 
         if (text.isEmpty()) {   // see if x/o assigned yet
           sourceBtn.setText(....);  / "X" or "O" depending on logic
         }
    }
    

    这样,所有 9 个按钮可以共享完全相同的 ActionListener,程序仍然可以工作。


    编辑
    您在评论中声明:

    为什么是 trim()?

    我认为您在这里进行了井字游戏,如果是这样,您不想将“X”添加到已经显示 X 或 O 文本的 JButton。如果您给 JButton 一个空格 " " 用于文本,trim() 将去掉任何前导或尾随空格并将文本更改为 "",您将知道它可以接受新文本,“X”或“O”。如果您不需要它,请不要使用它。

    【讨论】:

    • 谢谢,成功了!但我只写了: JButton sourceButton = (JButton) e.getSource(); sourceButton.setText("X");为什么是 trim() 的东西?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2012-09-19
    • 1970-01-01
    相关资源
    最近更新 更多