【问题标题】:2D Button Array ActionListener, color change?2D Button Array ActionListener,颜色变化?
【发布时间】:2012-03-22 07:50:34
【问题描述】:

我有这个 2D JButton 数组(白色),我想要做的是当我点击一个正方形时,它会变成橙色。当我单击另一个方块时,该方块也会变为橙色,但我单击的第一个方块将恢复为正常的白色。在不让所有方块都变成橙色的情况下,我该怎么做?

这是一个可视化:

顺便说一句,当我单击带有数字的方块时,它们的颜色不会改变,将它们视为setEnabled(false) 按钮。我已经知道如何更改按钮的颜色,我只想知道颜色是如何逐个正方形传递的。

感谢任何可以提供帮助的人!

编辑:我的“尝试”,但它使我所有的 null 有价值的按钮变成橙色。

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

【问题讨论】:

  • What have you tried?你到底卡在哪里了?不过,为了我的钱,如果按钮除了变色之外没有内在的“动作”,我会使用 JLabel 和 MouseListener,但需要记住将 JLabel 的 opaque 属性设置为 true 以便它们绘制他们的背景颜色。
  • 您可以很好地使用 JToggleButtons 数组,如需更好的帮助,请尽快使用SSCCE编辑您的帖子
  • @HovercraftFullOfEels 我尝试在我的 actionListener 中创建 JButton 的实例,如下所示:ae.getSource() instanceof JButton 但当我单击它们时,它会使我的所有按钮变为橙色。
  • @Hover 你想挑战截屏的 Van Gui 来进行截屏吗?现在你是乐观的人!我们即将看到充满印象派的气垫船吗? ;)
  • @Andrew:更像是 Hovercraft-full-of-chit。我们会看到,我们会看到。

标签: java swing colors jbutton multidimensional-array


【解决方案1】:

您可以使用JToggleButton 并将它们放在ButtonGroup 中,这样您就可以将它们视为一个组并将颜色设置为激活的组。

附:如果有任何问题,我将在接下来的 24 小时内与此线程保持联系,我会尝试解释更多。

【讨论】:

  • 谢谢!我今晚试试看。
  • 酷!有效!非常感谢!我不打算再把颜色改成橙色了:)
【解决方案2】:
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) 方法中试试上面的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2012-06-19
    • 2021-04-08
    • 2015-08-06
    • 2013-11-26
    • 2011-04-12
    相关资源
    最近更新 更多