2015-08-27 62 views
0

在大幅度縮短我的代碼的兩個語句中,我需要添加一個將JButton的文本添加到StringBuilder的語句。 ActionListener語句存在可以在單擊時禁用JButton(一個很好的美學),但是我想包括如果可能的話,還可以在ActionListener中追加StringBuilder。以下是這段代碼的兩部分。更改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); 
    } 

當由for循環產生的.addActionListener(disableButton)增加了上述的ActionListener到每個按鈕。然而,

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

是什麼,我認爲會適當追加StringBuilder的 「currentWord」 與任何值點擊按鈕保存(因此 「((JButton的)event.getSource())」)。每個說法都沒有錯誤,但我在主類中編寫了單獨的代碼行,以便在單擊任何按鈕時測試StringBuilder是否有任何更改。沒有。

在哪裏以及我需要做些什麼才能正確添加點擊JButton的值到currentWord?

回答

4

使用(JButton)event.getSource()將導致StringBuilder調用對象toString方法。這是不是你想要的,相反,要麼使用JButtontext財產或ActionEventactionCommand特性,例如...

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

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

代替

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

+0

謝謝,完美的作品。 –

+0

@SemicolonCapitalD很高興它可以提供幫助 – MadProgrammer