Java swing 显示问题
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class DrawHouse extends JFrame
{
public DrawHouse()
{
super( "House ");
setSize(600,600);
setVisible(true);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.blue);
g.drawRect(100, 250, 200, 150);
g.drawLine(100, 250, 200, 175);
g.drawLine(300, 250, 200, 175);
g.drawLine(300, 250, 400, 175);
g.drawLine(300, 400, 400, 325);
g.drawLine(400, 325, 400, 175);
g.drawLine(400, 175, 300, 125);
g.drawLine(200, 175, 300, 125);
}
public static void main(String[] args)
{
DrawHouse draw=new DrawHouse();
}
}
在eclipse上运行时,有时候能显示出来图形,有时候把JFrame刷几次才显示出来,感觉代码没有问题,哪位高手能帮个忙?
------解决方案--------------------没问题啊,每次都正常显示了图形.
大概是你电脑虚拟机的问题吧.
我家里是98,运行次数多了,也会出错的.
------解决方案--------------------运行几遍都正常
------解决方案--------------------你最好不要让Frame去画这个东西,而应该让里面的panel做
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawHouse extends JFrame
{
public DrawHouse()
{
super( "House ");
setSize(600,600);
setVisible(true);
this.setContentPane(new JPanel(){
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.blue);
g.drawRect(100, 250, 200, 150);
g.drawLine(100, 250, 200, 175);
g.drawLine(300, 250, 200, 175);
g.drawLine(300, 250, 400, 175);
g.drawLine(300, 400, 400, 325);
g.drawLine(400, 325, 400, 175);
g.drawLine(400, 175, 300, 125);
g.drawLine(200, 175, 300, 125);
}
});
}
public static void main(String[] args)
{
DrawHouse draw=new DrawHouse();
}
}