是的,这是作业。是的,我完全陷入困境。
这是要点。我创建了一个 JFrame。有 3 个面板(顶部、中间、底部)。底部面板中有 3 个按钮:红色、绿色和蓝色。顶部面板中有 3 个文本字段,用于显示单击相应按钮的次数。每个按钮最多允许 10 个。中间的面板是一个 8 x 8 的 Jbutton 网格,编号从 0 到 63。到目前为止,一切顺利。
每次我们单击一个按钮,就会启动一个线程。没有线程会死亡 当线程启动时,会随机选择 0 到 63 之间的数字。与该数字对应的 JButton 将被涂上单击的颜色。因此,如果单击红色按钮,我们应该看到一个白色背景的框变成红色。但随后该 JButton 的颜色开始褪色,直到变成白色。该过程大约需要 8 秒。
您创建的线程不应访问任何 Swing 组件。相反,人们必须维护一种数据结构,并根据线程的执行周期进行更新。另一方面,定期从主线程调用 repaint() 方法,以邀请 Swing Event Dispatcher 线程最终访问数据结构的内容并相应地显示 GUI 组件。
........我已经获得了所有创建和显示的对象。您不能点击某个按钮超过 10 次。这是我现在的位置:
我有两个数组:一个是大小为 64 的字符串数组。它们代表按钮。我还有一个整数数组。这样我就可以知道线程的创建顺序。我在单击按钮时创建了线程,并启动了它们。这是我的线程运行方法:
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 方法由事件调度线程处理。 (请注意,上面的代码仅适用于红色线程。其想法是通过逐渐增加绿色和蓝色直到变成白色来淡化颜色。
问题:当我单击底部的红色按钮时,没有按钮改变颜色(是的,已完成适当的注册。)我也不知道如何控制多个线程运行的时间。我在这里走的是正确的道路吗?
最佳答案
在不透露太多的情况下,这个 example说明了一种处理忽略 setBackground()
的颜色和按钮的方法。示例 here和 here演示如何褪色。由于两者都依赖于 javax.swing.Timer
线程,因此两者都不是解决方案,但这些技术可能会很有用。
关于java - Swing、Java 和多线程以及着色按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9498389/