在 gridLayout | 上读取和存储多个 JButton 的随机值 Java SWING

我正在尝试将查找三元组练习实现为 SWING GUI,其中有一个随机数网格,用户单击三个数字。如果前两个加起来等于第三个,它会增加正确尝试的计数器。试图了解如何将每个单击的数字存储在一个对象中,以便检查正确性。

我试图了解我应该在哪里实现 actionListener,在 Square 类或 Board 类,以及如何获取和存储每个单击按钮的值

这是我在获取第一个值的过程中得到的,但不知道如何在 actionListener 之外读取它,或者如何获取其他值。

private class ButtonListener implements ActionListener {

        @Override

        public void actionPerformed(ActionEvent e) {

            if(e.getSource()==finish)

                JOptionPane.showMessageDialog(null, "You made " + wrongs + "correct tries.");

            else{

                Square sqr = (Square) e.getSource();

                int num = sqr.getNum();

            }

        }

    }

我想了解如何解决此类问题的原理。我觉得需要采取一种完全不同的方法。


慕运维8079593
浏览 92回答 1
1回答

慕田峪4524236

解决方案不是唯一的,但resposte是取决于。如果你想用 numbar 给出点击的顺序,我认为使用 List 会更好。如果你只想给出总和的结果,最好使用 unique veriable。一个示例解决方案,假设我们使用具有全局可见性的组件(虽然面向对象编程不推荐这些具有全局可见性的组件)public class SingletonGame{&nbsp; &nbsp; private static final SingletonGame SINGLETON = new SingletonGame();&nbsp; &nbsp; public static SingletonGame getInstance(){&nbsp; &nbsp; &nbsp; &nbsp; return SINGLETON;&nbsp; &nbsp; }&nbsp; &nbsp; private int sum;&nbsp; &nbsp; //or&nbsp; &nbsp; private List<Integer> operations = new ArrayList<>();&nbsp; &nbsp; private SingletonGame(){}&nbsp; &nbsp; public int getSum(){&nbsp; &nbsp; &nbsp; &nbsp; return sum;&nbsp; &nbsp; }&nbsp; &nbsp; //or&nbsp; &nbsp; public List<Integer> getOperations(){&nbsp; &nbsp; &nbsp; &nbsp; return operations;&nbsp; &nbsp; }&nbsp; &nbsp; public void addSum(int num){&nbsp; &nbsp; &nbsp; &nbsp; this.sum += num;&nbsp; &nbsp; }&nbsp; &nbsp; //or&nbsp; &nbsp; public void addOp(int num){&nbsp; &nbsp; &nbsp; &nbsp; this.operations.add(num);&nbsp; &nbsp; }&nbsp; &nbsp; publi void getResult(){&nbsp; &nbsp; &nbsp; &nbsp; //inside this method you have your logic&nbsp; &nbsp; &nbsp; &nbsp; //for calculate result&nbsp; &nbsp; }}//Inside your actionprivate class ButtonListener implements ActionListener {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void actionPerformed(ActionEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(e.getSource()==finish)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JOptionPane.showMessageDialog(null, "You made " + wrongs + "correct tries.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Square sqr = (Square) e.getSource();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int num = sqr.getNum();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // you must do control when is case for call SingletonGame.getInstance().getResult();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SingletonGame.getInstance().sum(num);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java