我正在尝试通过更改颜色并调用 repaint()
方法来刷新 Java 图形对象。颜色仅随着最终更改颜色调用而更新。这是我的代码:
public void start() {
try {
Color origColor = node.getColor();
for (int i=0; i<noOfFlashes; i++) {
Manager.gui.getDrawGraph().changeNodeColor(node, Color.WHITE);
Thread.sleep(500);
Manager.gui.getDrawGraph().changeNodeColor(node, origColor);
Thread.sleep(500);
}
Manager.gui.getDrawGraph().changeNodeColor(node, Graph.VISITED_NODE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
改变节点颜色的方法是:
public void changeNodeColor(Node node, Color c) {
node.setColor(c);
repaint();
}
更改节点颜色与绘制组件属于同一类。
任何帮助将不胜感激。
最佳答案
您需要使用单独的线程来管理 GUI 事件。
您可以使用SwingWorker来做到这一点,按照 Amine 的建议,或实现 Runnable接口(interface),或扩展Thread类,开发 run()
方法,那就是你的线程的任务。
您可以阅读SO的这个老问题:How do I use SwingWorker in Java?
SwingWorker 教程:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
创建主题的教程:http://docs.oracle.com/javase/tutorial/essential/concurrency/
The color is only updating with the final change color call.
如果你不使用单独的线程,你的 gui 将卡住,直到该方法完全执行,并且你不会看到由 Thread.sleep(500);
分隔的颜色变化。 .
更新
在 this链接,在为什么 Swing GUI 卡住或锁定?段落中,您可以通过使用单线程来理解为什么 Java Swing GUI 卡住。
另请检查this官方链接,在创建线程段落中,以及this页面,返回:
Swing's single-thread rule says that Swing components can only be accessed by a single thread. This rule applies to both gets and sets, and the single thread is known as the event-dispatch thread.
The single-thread rule is a good match for UI components because they tend to be used in a single-threaded way anyway, with most actions being initiated by the user. Furthermore, building thread safe components is difficult and tedious: it's a good thing not to be doing if it can be avoided. But for all its benefits, the single-thread rule has far-reaching implications.
Swing components will generally not comply with the single-thread rule unless all their events are sent and received on the event-dispatch thread. For example, property-change events should be sent on the event-dispatch thread, and model-change events should be received on the event-dispatch thread.
For model-based components such as JTable and JTree, the single-thread rule implies that the model itself can only be accessed by the event-dispatch thread. For this reason, the model's methods must execute quickly and should never block, or the entire user interface will be unresponsive.
我认为上面的句子对于更好地理解Swing
非常有用。包。
我报告了trashgod的建议。
您可以使用Timer
类,来自javax.swing.Timer
包裹。这也是一个不错的选择。
在 this问题,trashgod 报告了一些 Timer
的例子.
检查here有关 Timer
的教程.
关于java - 更改 Java 图形对象的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8259127/