我是GUI编程的新手,我尝试了一些代码,并希望不断更改名为“HeaderPanel”的JPanel的背景。
为什么这不能按我的意愿运作? (颜色保持不变......)
private void changeColors() {
int r = 0;
int g = 155;
int b = 12;
while(true) {
r = (r+1)%255;
g = (g+1)%255;
b = (b+1)%255;
Color color = new Color(r,g,b);
HeaderPanel.setBackground(color);
}
}
答案 0 :(得分:3)
你的while循环正在阻止重绘管理器改变颜色。
您需要,某些方法,在后台执行请求,类似这样的
public class TestLabel extends JLabel {
private Timer timer;
private int r = 0;
private int g = 155;
private int b = 12;
public TestLabel() {
setText("Hello world");
setOpaque(true);
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("tick");
r = (r + 1) % 255;
g = (g + 1) % 255;
b = (b + 1) % 255;
Color color = new Color(r, g, b);
setBackground(color);
System.out.println(color);
if (r == 0 && b == 0 && g == 0) {
r = 0;
g = 155;
b = 12;
}
invalidate();
revalidate();
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
}
您可能希望阅读
使用扩展示例更新
public class TestLabel extends JLabel {
private Timer timer;
private Object[][] colors = {{"Black", Color.BLACK},
{"Blue", Color.BLUE},
{"Cyan", Color.CYAN},
{"Dark Gray", Color.DARK_GRAY},
{"Gray", Color.GRAY},
{"Green", Color.GREEN},
{"Light Gary", Color.LIGHT_GRAY},
{"Mangenta", Color.MAGENTA},
{"Orange", Color.ORANGE},
{"Pink", Color.PINK},
{"Red", Color.RED},
{"White", Color.WHITE},
{"Yellow", Color.YELLOW}};
public TestLabel() {
setText("Hello world");
setOpaque(true);
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("tick");
int index = (int) Math.round((colors.length - 1) * Math.random());
Object[] group = colors[index];
setBackground((Color)group[1]);
setText((String)group[0]);
}
});
timer.setInitialDelay(0);
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
}
答案 1 :(得分:0)
我不是摇摆开发者,但是当你改变颜色属性时,你不需要“重画”或类似的东西吗? 另一方面,您需要另一个线程来不断更新颜色。
综述
答案 2 :(得分:-1)
您需要告诉您的JPanel
自己画画,可能是致电invalidate()
。