【发布时间】:2017-03-20 09:53:41
【问题描述】:
我似乎没有完全理解paintcomponent方法包括repaint的使用。 有几次我不明白为什么重绘在某些代码中不起作用,而在另一个代码中工作正常。 我正在尝试创建一个图形绘画类。现在它的y = x。但它不会工作。油漆组件似乎只被调用了一次。这是为什么呢?
public class Graph extends JPanel
{
private int oldX=0,oldY=0,newX=1,newY=1;
public Graph()
{
invokeInitWindow();
}
public void invokeInitWindow()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
init();
}
});
}
public void init()
{
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(300,300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setVisible(true);
}
public void move()
{
newY=++newX;
oldX=oldY=newX+1;
}
public void runGraph()
{
while(newX < 500)
{
move();
repaint();
}
}
public static void main(String[] args)
{
Graph g = new Graph();
g.runGraph();
}
public void paintComponent(Graphics g)
{
g.setColor(Color.BLACK);
g.drawLine(oldX, oldY, newX, newY);
}
}
【问题讨论】:
-
是的,但是你
while-loop跑得太快了,在帧出现在屏幕上之前就完成了