用Swing编写灵敏的图形用户界面

http://tech.ddvip.com   2006年11月27日    社区交流

本文详细介绍用Swing编写灵敏的图形用户界面

  为了解决这个问题,有人也许会试图通过调用repaint()方法来更新组件:

final String[] str = new String[1];
this.jTextArea1.setText("Please wait...");
this.repaint();
try {
 Thread.sleep(1000L);
}catch(InterruptedException e) {
 e.printStackTrace();
}
str[0] = "Done.";
jTextArea1.setText(str[0]);

  但是这一个方法没有起到预期的作用,按钮仍然定住一段时间,在察看了repaint()方法的源代码之后就知道原因了。

PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE,
new Rectangle(x, y, width, height));
Toolkit.getEventQueue().postEvent(e);

  repaint()方法实际上是在事件队列里加了一个UPDATE的事件,而没有直接去重画组件,而且这一个事件只能等待当前的事件响应方法结束之后才能被分配。因此只有绕过分配机制直接调用paint方法才能达到目的。

final String[] str = new String[1];
this.jTextArea1.setText("Please wait...");
this.paint(this.getGraphics());
try {
 Thread.sleep(1000L);
}catch(InterruptedException e) {
 e.printStackTrace();
}
str[0] = "Done.";
jTextArea1.setText(str[0]);

  这样却是实现了更新,但是还存在着以下的问题。虽然从感觉上,按钮已经弹起来了,但是在Done.出现之前,我们却无法按下这个按钮。可以说按钮还是定住了,只不过定在了弹起的状态。调用重绘方法无法从根本上解决问题,因此我们需要寻求其他的方法。

  使用多线程

责编:豆豆技术应用

正在加载评论...