如何在 JFrame 中以正确的方式实现计时器
how to implement timer the right way in JFrame
我正在努力寻找如何让这个程序中的重点用计时器改变每一秒或每两秒。我尝试了一些组合,但都没有成功。
我相信 ActionListener 中有些东西我可能会失败。
ArrayList<Point> punkter = new ArrayList<Point>();
int i = 0;
int n = 0;
public Point[] point = null;
private Timer timer;
Random rg = new Random();
public timer(){
this.setTitle("Draw");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1010, 710);
this.setLayout(null);
this.setLocationRelativeTo(null);
point = new Point[100];
this.setVisible(true);
timer = new Timer(500,this);
timer.start();
}
public void paint(Graphics g){
super.paint(g);
for (int i = 0; i < punkter.size(); i++) {
Point a = punkter.get(i);
Point b = punkter.get((i+1)%punkter.size());
g.fillOval(a.x, a.y, 5, 5);
g.drawLine(a.x, a.y, b.x, b.y);
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
for(int i = 0;i < 100;i++){
point[i] = new Point(rg.nextInt(1000), rg.nextInt(700));
punkter.add(point[i]);
}
}
}
重绘时调用组件的repaint()方法,否则可能无法调用paintComponent(或paint)方法。可能不直接相关但值得给出的建议(并在 trashgod 的评论中指出):使用添加到 JFrame 的组件(如 JPanel),并在该组件的 paintComponent 方法中执行所有绘图(如果这样做,您应该在此组件上调用重绘)。
我正在努力寻找如何让这个程序中的重点用计时器改变每一秒或每两秒。我尝试了一些组合,但都没有成功。 我相信 ActionListener 中有些东西我可能会失败。
ArrayList<Point> punkter = new ArrayList<Point>();
int i = 0;
int n = 0;
public Point[] point = null;
private Timer timer;
Random rg = new Random();
public timer(){
this.setTitle("Draw");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1010, 710);
this.setLayout(null);
this.setLocationRelativeTo(null);
point = new Point[100];
this.setVisible(true);
timer = new Timer(500,this);
timer.start();
}
public void paint(Graphics g){
super.paint(g);
for (int i = 0; i < punkter.size(); i++) {
Point a = punkter.get(i);
Point b = punkter.get((i+1)%punkter.size());
g.fillOval(a.x, a.y, 5, 5);
g.drawLine(a.x, a.y, b.x, b.y);
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
for(int i = 0;i < 100;i++){
point[i] = new Point(rg.nextInt(1000), rg.nextInt(700));
punkter.add(point[i]);
}
}
}
重绘时调用组件的repaint()方法,否则可能无法调用paintComponent(或paint)方法。可能不直接相关但值得给出的建议(并在 trashgod 的评论中指出):使用添加到 JFrame 的组件(如 JPanel),并在该组件的 paintComponent 方法中执行所有绘图(如果这样做,您应该在此组件上调用重绘)。