2012-03-04 218 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)方法中试试上面的代码。