Joe*_*e C 2 java swing jbutton background-color
现在我通过使用改变按钮的背景颜色
button.setBackground(Color.WHITE);
Run Code Online (Sandbox Code Playgroud)
这是一个例子.
但是当我有一个巨大的网格jbuttons(1000+)时,只需运行for循环来改变每个按钮的背景是非常非常慢的.你可以看到网格慢慢变白,一帧一帧.我真的不想要这个
有没有更好的方法将网格上的每个JButton同时更改为相同的颜色?
这就是我制作网格的方式,所使用的数字仅仅是例如......
grid = new JPanel(new GridLayout(64, 64, 0, 0));
Run Code Online (Sandbox Code Playgroud)
这是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();
Run Code Online (Sandbox Code Playgroud)
您看到单独重新绘制框的事实表明关闭了双缓冲,或者按钮UI中的绘图代码使用了该缓冲paintImmediately().
我使用64x64 JButtons测试了您的设置,确保所有UI操作都在EDT(事件调度线程)中执行.我可以确认你看到的效果,改变所有按钮的背景花了大约1200毫秒,每个盒子立即重新粉刷.您可以通过将网格设置为不可见之前绕过立即重绘,并在更改背景后显示:
grid.setVisible(false);
for (Component comp : grid.getComponents()) {
comp.setBackground(color);
}
grid.setVisible(true);
Run Code Online (Sandbox Code Playgroud)
这导致网格只进行一次重绘,并将时间减少到~300ms(因子4).
这对于频繁更新来说仍然太慢,所以如果你想让网格单元格成为任意组件,你最好使用绘制网格的自定义组件或flyweight容器(评论中建议的trashgod) .