簡體   English   中英

更改ActionListener以追加StringBuilder

[英]Changing ActionListener to append StringBuilder

在兩個大大縮短了我的代碼的語句中,我需要添加一條將JButton的文本添加到StringBuilder的語句。 存在ActionListener語句以在單擊時禁用JButton(一種很好的美感),但是我想盡可能包括在ActionListener中附加StringBuilder的功能。 以下是此代碼的兩部分。

theModel.randomLetters();

    ActionListener disableButton = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            if (!(event.getSource() instanceof JButton)) {
                return;
            }
            theModel.currentWord.append((JButton)event.getSource());
            ((JButton)event.getSource()).setEnabled(false);
        }
    };

    for (int i = 0; i < 16; i++) {
        JButton dice = new JButton(theModel.letters.get(i));
        dice.addActionListener(disableButton);
        boggleGrid.add(dice);
    }

.addActionListener(disableButton)將上述ActionListener添加到由for循環生成的每個按鈕上。 然而,

                theModel.currentWord.append((JButton)event.getSource());

我認為應該將StringBuilder“ currentWord”適當地附加到單擊按鈕所具有的任何值上(因此為“(((JButton)event.getSource())”))。 每個發言都沒有錯誤,但是我在主類中編寫了單獨的代碼行,以測試單擊任何按鈕時StringBuilder是否有任何更改。 沒有。

我需要在何處以及如何將單擊的JButton的值正確添加到currentWord?

使用(JButton)event.getSource()將導致StringBuilder調用對象toString方法。 這不是您想要的,而是使用JButtontext屬性或ActionEventactionCommand屬性,例如...

theModel.currentWord.append(((JButton)event.getSource()).getText());

要么

theModel.currentWord.append(event.getActionCommand());

代替

除非您自己指定JButtonactionCommand ,否則它將使用按鈕文本作為actionCommand

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM