【发布时间】:2019-05-31 20:28:48
【问题描述】:
我有一个学生正在为学校的期末项目制作西蒙游戏,我整天都在尝试解决她的问题。 她正在尝试创建游戏西蒙。该程序随机选择一系列颜色并通过将 4 个彩色按钮的颜色从常规颜色更改为白色几秒钟然后返回来突出显示这些颜色。 编程不是一次突出一种颜色为白色,而是使所有颜色同时显示为白色。所以用户不知道顺序。
我一直在查找运行多个线程的问题,并尝试使用 .join() 函数。但是,当使用它时,没有颜色会变白。
//突出显示当前在数组中的颜色
public void play() {
//loop through the array and look at all the colours so far
for(int i=0; i<round;i++){
//red is the position in the array
if(colours[i]==1){
Thread sleep=new Thread(new Runnable(){
@Override
public void run(){
//change the colour of the red button to white
redButton.setBackground(Color.WHITE);
redButton.setOpaque(true);
//wait
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
//change the colour back
redButton.setBackground(Color.RED);
redButton.setOpaque(false);
}
});
sleep.start();
}
//yellow
else if(colours[i]==2){
Thread sleep=new Thread(new Runnable(){
@Override
public void run(){
yellowButton.setBackground(Color.WHITE);
yellowButton.setOpaque(true);
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
yellowButton.setBackground(Color.YELLOW);
yellowButton.setOpaque(false);
}
});
sleep.start();
}
//green
else if(colours[i]==3){
Thread sleep=new Thread(new Runnable(){
@Override
public void run(){
greenButton.setBackground(Color.WHITE);
greenButton.setOpaque(true);
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
greenButton.setBackground(Color.GREEN);
greenButton.setOpaque(false);
}
});
sleep.start();
}
//blue
else if(colours[i]==4){
Thread sleep=new Thread(new Runnable(){
@Override
public void run(){
blueButton.setBackground(Color.WHITE);
blueButton.setOpaque(true);
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
blueButton.setBackground(Color.CYAN);
blueButton.setOpaque(false);
}
});
sleep.start();
}
}
}
【问题讨论】:
-
那些按钮,
JButtons来自 Swing?在那种情况下,我根本不会使用线程。我会使用javax.swing.Timer来安排不同的屏幕颜色变化。
标签: java multithreading join