2012-02-29 24 views
2

是的,这是作业。是的,我完全卡住了。Swing,Java和多线程以及着色按钮

这是要点。我创建了一个JFrame。有3个面板(顶部,中部,底部)。在底部面板中有3个按钮,称为:红色,绿色和蓝色。在顶部面板中有3个文本字段,它们给了我们点击相应按钮的次数。我们允许的最大数量为每个按钮10个。在中间面板是一个8×8的Jbuttons网格,编号从0到63.到目前为止,这么好。

每当我们点击一​​个按钮,一个线程就开始了。没有线程死亡当线程开始时,随机选择一个从0到63的数字。与该号码对应的JButton被涂上了被点击的颜色。所以如果点击红色按钮,我们应该看到一个白色背景的框变为红色。但是那个JButton的颜色开始消失,直到它变成白色。这个过程大概需要8秒。

您创建的线程应该无权访问任何Swing组件。相反,必须维护一个数据结构,并根据执行周期由线程进行更新。另一方面,定期从主线程调用repaint()方法来邀请Swing Event Dispatcher线程最终访问数据结构的内容并相应地显示GUI组件。

........我已经获得了所有创建和显示的对象。您无法在按钮上点击10次以上。这里是我的位置:

我有两个数组:一个是大小为64的字符串数组。它们表示按钮。我也有一系列整数。这是为了让我知道线程创建的顺序。我点击了一个按钮创建了线程,并且已经启动了它们。下面是我对线程的run方法:

public void run() { 
    Random num = new Random(new Date().getTime()); 
    while (true) { 
     Thread j = Thread.currentThread(); 
     int randInt = num.nextInt(64); 
     synchronized (lock) { 

      if ((array[randInt].compareTo("red") == 0 
       || array[randInt].compareTo("blue") 
       == 0 || array[randInt].compareTo("green") == 0)) 
      { 
       randInt = num.nextInt(64); 
      } 
      for (int k = 0; k < 10; k++) { 
       if (threadarray[k] == -1) { 
        threadarray[k] = randInt; 
        break; 
       } 
      } 

     } 
    } 
} 

即使我们还没有涉及,我曾尝试使用Timer对象立即熄灭外面锁段。这将我带到actionPerformed方法。我已经添加了所有适当的注册。

public void actionPerformed(ActionEvent arg0) { 
    for (int i = 0; i < threadarray.length; i++) { 

     int num = threadarray[i]; 
     if (num != -1) { 
      System.out.println(num); 
      String s = array[num]; 
      System.out.println(s + "is "); 
      if (s.compareTo("red") == 0) { 
       button[num].setOpaque(true); 
       button[num].setBackground(Color.red); 
       while (button[num].getBackground() != Color.white) { 
        System.out.println("not white yet"); 
        int g = button[num].getBackground().getGreen(); 
        int b = button[num].getBackground().getBlue(); 
        if (255 - (g + 1) >= 0) { 
         Color c = new Color(255, g + 1, b + 1, 1); 
         button[num].setOpaque(true); 
         button[num].setBackground(c); 
         System.out.println(c + " " + " c is"); 
        } else { 
         button[num].setBackground(Color.white); 
        } 
       } 
      } 

      System.out.println(i + " i is " + button[num].getBackground()); //just some debugging info 
      threadarray[i] = -1; //clear the thread array 
      array[num] = "0"; //clear the string array 

     } 
    } 
} 

actionPerformed方法由Event Dispatch Thread处理。 (请注意,上面的代码仅适用于红色线程,想法是通过增加绿色和蓝色,直到它变成白色来淡化颜色。

问题:单击红色按钮时没有任何按钮会改变颜色(是的,已经完成了适当的注册)我也不知道如何通过多线程来控制时间,我是否会在这里走上正确的道路?

+0

如果是家庭作业,然后把'家庭作业'标签。 – Tudor 2012-02-29 11:38:32

+2

更好地帮助您更快地编辑您的问题[SSCCE](http://sscce.org/) – mKorbel 2012-02-29 11:44:38

+2

也请解释更多问题是什么?你没有看到按钮颜色的变化,但你看到actionPerformed的文本输出吗? – toto2 2012-02-29 11:55:48

回答

2

没有放弃太多, example举例说明了一种处理颜色和忽略setBackground()的按钮的方法。示例herehere演示了如何淡入颜色。由于两者都依赖于线程,因此两者都不是解决方案n,但这些技巧可能会有用。