【发布时间】:2011-09-01 08:28:59
【问题描述】:
现在我使用
更改按钮的背景颜色button.setBackground(Color.WHITE);
这是一个例子。
但是当我有一个巨大的 jbuttons 网格(1000+)时,只需运行一个 for 循环来更改每个按钮的背景非常非常慢。您可以看到网格逐渐变白,逐个框。我真的不想要这个
有没有更好的方法将网格上的每个 JButton 同时更改为相同的颜色?
这就是我制作网格的方式,使用的数字仅用于示例...
grid = new JPanel(new GridLayout(64, 64, 0, 0));
这是 4096 个按钮,大约需要 30 多秒才能将每个按钮更改为相同的颜色。
编辑 1:我需要按钮是可点击的,例如当我点击一个按钮时它会变成蓝色。单击所有按钮后,将每个按钮的颜色更改为白色。现在我可以正常工作,但是更改每个按钮的颜色很慢。
编辑 2:这就是我更改按钮的方式:
new javax.swing.Timer(300, new ActionListener() {
int counter = 0;
public void actionPerformed(ActionEvent e) {
if (counter >= counterMax) {
((Timer) e.getSource()).stop();
}
Color bckgrndColor = (counter % 2 == 0) ? flashColor : Color.white;
for (JButton button : gridButton) {
button.setBackground(bckgrndColor);
}
counter++;
}
}).start();
【问题讨论】:
-
考虑在这里使用 JTable 而不是充满按钮的 GridLayout。
-
另外,您在哪个线程中进行背景设置?尝试在事件调度线程中执行此操作(使用 (
SwingUtilities|EventQueue).(invokeLater|invokeAndWait)(...))。
标签: java swing background-color jbutton