摆脱循环,但需要保持运行?
我已经四处走动(圆圈),但是现在我的应用程序无法继续执行其他任务,因为我被陷入困境时。
我该如何摆脱困境,仍然让我的圈子在后台移动?
- 我知道这是因为我一直在调用方法 draw(); ,但是我还应该如何绘制这个圆圈?
public class MyFrame extends JPanel {
int xc = 150, yc = 150, r = 100, diam = 50;
double inc = Math.PI/360, theta = 0;
public void draw(Graphics g) {
Timer timer = new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
theta = theta+inc;
repaint();
System.out.println(theta);
}
});
timer.setDelay(20);
timer.start();
}
@Override
public void paint(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); //smooth the border around the circle
g2d.rotate(theta, xc, yc);
g2d.setColor(Color.blue);
g2d.drawOval(xc + r - diam / 2, yc + r - diam / 2, diam, diam);
draw(g);
}
}
I've made a circle move around (in a circle), but now my application won't move on to the other tasks as I got myself caught in a loop.
How do I get out of this and still have my circle moving in the background?
- I know it is because I keep calling the method draw();, but how should I else keep this circle being drawn?
public class MyFrame extends JPanel {
int xc = 150, yc = 150, r = 100, diam = 50;
double inc = Math.PI/360, theta = 0;
public void draw(Graphics g) {
Timer timer = new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
theta = theta+inc;
repaint();
System.out.println(theta);
}
});
timer.setDelay(20);
timer.start();
}
@Override
public void paint(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); //smooth the border around the circle
g2d.rotate(theta, xc, yc);
g2d.setColor(Color.blue);
g2d.drawOval(xc + r - diam / 2, yc + r - diam / 2, diam, diam);
draw(g);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将循环,计时器与绘画分开。让计时器更改密钥变量的状态,然后调用重新粉刷。因此,您可以创建并启动绘画方法的外部计时器,例如在构造函数中,并让PaintComponent专注于一件事,单独使用一件事,绘画,不改变状态:
Separate the looping, the timer, from the painting. Let the timer change the state of the key variable(s) and then call repaint. So you can create and start the Timer outside of a painting method, such as within a constructor, and leave the paintComponent to concentrate on one thing and one thing alone, painting, and not changing state: