求助——有Thread.sleep(100)能画线,无Thread.sleep(100)就不能画线 是为什么?

hdgrws 2016-07-30 06:17:31
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

public class DrawLine extends JFrame {
private Thread t;
public DrawLine(){
setBounds(600,300,600,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics graphics = getGraphics();
graphics.setColor(Color.RED);
for(int y=50;y<100;y++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}

graphics.drawLine(30, y, 100, y);
y++;
}
}
public static void main(String[] args) {
new DrawLine();
}

}

...全文
188 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
NewMoons 2016-08-01
  • 打赏
  • 举报
回复
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class DrawLine extends JFrame { public DrawLine() { setBounds(600, 300, 600, 400); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void draw() { Graphics graphics = getGraphics(); graphics.setColor(Color.RED); for (int y = 50; y < 100; y++) { graphics.drawLine(30, y, 100, y); y++; } } public static void main(String[] args) { final DrawLine jframe = new DrawLine(); SwingUtilities.invokeLater(new Runnable() { public void run() { jframe.draw(); } }); } } ui的操作一定要用线程来执行,这是swing的事件处理机制决定的,也是真正理解swing运行机制的核心内容之一。 具体解释可看下面的文章。 http://blog.csdn.net/helloxtayfnje/article/details/5461429 如果觉得还不理解,请再百度关键字 swing SwingUtilities
逗泥丸的平方 2016-08-01
  • 打赏
  • 举报
回复
试试 对JFrame使用 repaint()或者validate()
hdgrws 2016-08-01
  • 打赏
  • 举报
回复
@NewMoons 谢谢你,略懂了。
hdgrws 2016-08-01
  • 打赏
  • 举报
回复
引用 1 楼 qq_35209952 的回复:
试试 对JFrame使用 repaint()或者validate()
谢谢!只是看到有人用Graphics graphics = getGraphics(); ......感觉很好理解的样子。所以自己也试试,谁知道自己碰到问题了。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧