我想知道如何在点击JButton时启动'计时器'。我环顾四周,看看是否有与我的情况相关的答案,我找不到答案。
以下是我之前提问的代码示例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GreenRects extends JPanel {
private static final int SCREEN_WIDTH = 500;
private static final int SCREEN_HEIGHT = 500;
private static final int OFFSET = 100;
private static final int SIZE = 20;
private static final int INC = 5;
int[] xPoints = new int[5];
public GreenRects() {
int x = 0;
for (int i = 0; i < xPoints.length; i++) {
xPoints[i] = x;
x += OFFSET;
}
Timer timer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < xPoints.length; i++) {
if (xPoints[i] + INC < SCREEN_WIDTH) {
xPoints[i] += INC;
} else {
xPoints[i] = 0;
}
}
repaint();
}
});
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
g.setColor(Color.green);
for (int i = 0; i < xPoints.length; i++) {
g.fillRect(xPoints[i], 0, SIZE, SIZE);
}
}
public Dimension getPreferredSize() {
return new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT);
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new GreenRects());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
答案 0 :(得分:4)
首先,将timer
设为实例变量......
private static final int SCREEN_WIDTH = 500;
private static final int SCREEN_HEIGHT = 500;
private static final int OFFSET = 100;
private static final int SIZE = 20;
private static final int INC = 5;
int[] xPoints = new int[5];
// Add me here...
private Timer timer;
不要忘记删除旧的声明......
Timer timer = new Timer(50, new ActionListener() {
应该成为
timer = new Timer(50, new ActionListener() {
否则,您最终会得到一个阴影变量,并且可能会NullPointerException
。
接下来,创建一个JButton
并向其中添加ActionListener
,然后在其中调用timer.start()
JButton btn = new JButton("Start");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
现在,不要忘记将其添加到您的UI,以便用户可以单击它...
请查看How to use buttons了解详情
<强>更新强>
根据评论,我会向start
课程添加stop
甚至GreenRects
方法。这些会调用timer
....
public void start() {
timer.start();
}
从那里,当触发按钮ActionListener
时,您只需调用start
实例的GreenRects
方法...
public void actionPerformed(ActionEvent e) {
greenRects.start();
}
然后我会将按钮添加到其他容器中,这样就不会打断GreenRects
类正在绘制的内容......
答案 1 :(得分:1)
您正在创建一个ActionListener
,但您没有任何可听的内容。幸运的是,JButton
通过其AbstractButton
超类具有addAction
方法。通常通过其具体实现Action
创建AbstractAction
实例,并将其添加到按钮。 Action
优于ActionListener
的优势在于您也可以将其添加到JMenuItem
。