亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 gridLayout | 上讀取和存儲多個 JButton 的隨機值 Java SWING

在 gridLayout | 上讀取和存儲多個 JButton 的隨機值 Java SWING

慕運維8079593 2023-05-17 17:43:05
我正在嘗試將查找三元組練習實現為 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();? ? ? ? ? ? }? ? ? ? }? ? }我想了解如何解決此類問題的原理。我覺得需要采取一種完全不同的方法。
查看完整描述

1 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

解決方案不是唯一的,但resposte是取決于。

如果你想用 numbar 給出點擊的順序,我認為使用 List 會更好。

如果你只想給出總和的結果,最好使用 unique veriable。

一個示例解決方案,假設我們使用具有全局可見性的組件(雖然面向對象編程不推薦這些具有全局可見性的組件)

public class SingletonGame{


    private static final SingletonGame SINGLETON = new SingletonGame();


    public static SingletonGame getInstance(){

        return SINGLETON;

    }


    private int sum;

    //or

    private List<Integer> operations = new ArrayList<>();


    private SingletonGame(){}


    public int getSum(){

        return sum;

    }


    //or

    public List<Integer> getOperations(){

        return operations;

    }


    public void addSum(int num){

        this.sum += num;

    }


    //or

    public void addOp(int num){

        this.operations.add(num);

    }


    publi void getResult(){

        //inside this method you have your logic

        //for calculate result

    }


}


//Inside your action


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

                // you must do control when is case for call SingletonGame.getInstance().getResult();

                SingletonGame.getInstance().sum(num);


            }

        }

    }


查看完整回答
反對 回復 2023-05-17
  • 1 回答
  • 0 關注
  • 125 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號