使用线程更改数组中按钮的颜色 [英] Changing color of buttons in array using thread
本文介绍了使用线程更改数组中按钮的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想循环遍历一组按钮,并在迭代数组时将其颜色改变3次。当我单击数组的第一个按钮时,它会改变其余颜色,就像我想要的那样。当我再次尝试时,它不会在我的run()方法中运行try块。
这是代码。
I want to loop through an array of buttons, and change their colors 3 times as iterate through the array. When i click the first button of the array, it changes the colors of the rest, as i want it to. When i go and try it again, it does not run the try block in my run() method.
Here is the code.
public class ButtonWindow extends JFrame implements Runnable {
private JPanel topPanel = new JPanel(new GridBagLayout());
JButton[] listButtons = new JButton[5];
private Thread t;
public void run() {
System.out.println("Running thread");
try {
for(int i = 1; i < listButtons.length; i++) {
System.out.println("Thread changing colors");
listButtons[i].setBackground(Color.YELLOW);
Thread.sleep(1000);
listButtons[i].setBackground(Color.ORANGE);
Thread.sleep(1000);
listButtons[i].setBackground(Color.RED);
Thread.sleep(1000);
listButtons[i].setBackground(null);
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Thread closing.");
}//close run() method
public void start(){
System.out.println("Starting thread ");
if(t == null){
t = new Thread(this);
t.start();
}
}//close start() method
//CONSTRUCTOR
public ButtonWindow(){
//create the buttons
for(int i = 0; i < 5; i++){
listButtons[i] = new JButton(String.valueOf(i));
}
setSize(400,400);
setTitle("Colors");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buildTopPanel();
//BUTTON LISTENERS/////////////////////////////////////////////////////////////////////////////////
listButtons[0].addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Creating thread");
start();
}
});
//BUTTON LISTENERS END///////////////////////////////////////////////////////////////////
}//CLOSE CONSTRUCTOR
//CREATE PANEL
public void buildTopPanel(){
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
for(int i = 0; i < 5; i++){
//listButtons[i] = new JButton(String.valueOf(i));
gc.insets = new Insets(5, 10,0,0);
topPanel.add(listButtons[i],gc);
gc.gridy ++;
}
add(topPanel,BorderLayout.NORTH);
}
}//CLOSE CLASSS
推荐答案
那是因为t
不是null
第二个你运行start
方法的时间,所以线程永远不会再次启动。
尝试设置t
到null
在运行
方法的末尾,这将允许颜色循环重启。
希望这会有所帮助,
Fredrik
That's becauset
is notnull
the second time you run yourstart
method, so the thread never get's started again.
Try settingt
tonull
at the end of therun
method, that will allow the color-cycling to restart.
Hope this helps,
Fredrik
这篇关于使用线程更改数组中按钮的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文