2012-03-04 321 views
1

我有這個2D JButton數組(白色),我想要做的是當我點擊一個正方形時,它會變成橙色。當我點擊另一個正方形時,該正方形也會變成橙色,但我點擊的第一個正方形將恢復爲正常的白色。如果沒有將所有方塊變成橙色,我該怎麼做?2D按鈕數組ActionListener,顏色變化?

這裏有一個可視化: enter image description here

順便說一句,當我點擊與數字的平方,它們的顏色沒有改變,認爲他們是像setEnabled(false)按鈕。我已經知道如何改變按鈕的顏色,我只是想知道顏色如何在方形之後通過平方。

感謝任何人誰可以幫助!

編輯:我的「嘗試」,但它使我所有的價值橙色按鈕。

button[i][j].addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent e){ 
     for(int i = 0; i < button.length; i++) 
      for(int j = 0; j < button.length; j++){ 
       if(g.gameBoard[i][j] == null){ 
        //must find the position where the user clicks and make it orange 
        button[i][j].setBackground(Color.ORANGE); 
       } 
      } 
     } 
}); 
+1

[你有什麼試過](http://mattgemmell.com/2008/12/08/what-have-you-tried/)?你到底在哪裏卡住?不過,對於我的錢來說,如果按鈕沒有除了轉動顏色之外的內在「動作」,我會使用JLabels和MouseListener,但是需要記住將JLabel的opaque屬性設置爲true,以便它們可以繪製他們的背景顏色。 – 2012-03-04 16:29:07

+2

你可以漂亮地使用JToggleButtons數組,以便更快地獲得更好的幫助,請編輯你的文章[SSCCE](http://sscce.org/) – mKorbel 2012-03-04 16:32:11

+0

@HovercraftFullOfEels我試過在我的actionListener中創建JButton實例,如下所示: 'ae.getSource()instanceof JButton',但它讓我所有的按鈕變成橙色,當我點擊它們時。 – alicedimarco 2012-03-04 16:38:04

回答

3

可以使用JToggleButton,並把它們放在一個ButtonGroup,讓你可以把它們當作一個組,並設置顏色爲被激活的一個。

P.S.如果有任何問題我會盡力解釋,我會在接下來的24小時內保持與此主題的聯繫。

+0

謝謝!我今晚會嘗試一下。 – alicedimarco 2012-03-04 17:16:09

+0

酷!有效!非常感謝!我不打算改變顏色爲橙色了:) – alicedimarco 2012-03-05 06:55:50

-1
if(e.getSource()== null) 
{ 
    //must find the position where the user clicks and make it orange 
    button[i][j].setBackground(Color.ORANGE); 
} 

在public void actionPerformed(ActionEvent e)方法中試試上面的代碼。