问题是我没有得到任何错误,但计时器没有被添加到框架。反复“越来越”变化int
比方说我有三大类:InFrameClock,钟表和TwoPlayer
TimeKeeper的包含增加一个int “计数器” 每秒摆动计时器:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class TimeKeeper extends JPanel {
private Timer timer;
private int delay = 1000; // every 1 second
private ActionListener action;
private int counter = 0;
public TimeKeeper() {
action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
counter++;
};
};
}
public boolean isTimerRunning() {
return timer != null && timer.isRunning();
}
public void startTimer() {
timer = new Timer(delay, action);
timer.setInitialDelay(0);
timer.start();
}
public void stopTimer() {
if (timer != null && timer.isRunning()) {
timer.stop();
timer = null;
counter = 0;
}
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
}
^显然,这些都是其他地方使用,但我会到达那个有点
的TwoPlayer类启动和停止计时器:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TwoPlayer {
private JFrame mainFrame;
private TimeKeeper myTimeKeeper;
public TwoPlayer() {
mainFrame = new JFrame("Two Player");
mainFrame.setSize(325, 135);
mainFrame.setLocation(600, 300);
mainFrame.setLayout(new FlowLayout());
myTimeKeeper = new TimeKeeper();
JButton button1 = new JButton("Start/Stop");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (myTimeKeeper.isTimerRunning()) {
myTimeKeeper.stopTimer();
}
else {
myTimeKeeper.startTimer();
}
}
});
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
InFrameClock clock = new InFrameClock(myTimeKeeper);
mainFrame.setVisible(true);
mainFrame.add(button1);
mainFrame.add(clock);
}
}
上述被添加到帧的对象“时钟”来自下面的类:
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class InFrameClock extends JPanel{
private JLabel clock = new JLabel();
private int timeSec;
private int timeMin;
TimeKeeper myTimeKeeper;
public InFrameClock(TimeKeeper timeKeeper){
this.myTimeKeeper = timeKeeper;
int clockVal = timeKeeper.getCounter();
clock.setText(String.valueOf(clockVal));
while (clockVal <= 0){
clockVal = timeKeeper.getCounter();
if(clockVal >= 60){
timeSec = clockVal % 60;
timeMin = (clockVal - timeSec)/60;
clock.setText(String.valueOf(timeMin) +
":" + String.valueOf(timeSec));
}
else{
clock.setText(String.valueOf(clockVal));
}
setLayout(new GridBagLayout());
add(clock);
}
}
}
我觉得我在做什么:在TimeKeeper的初始化计数器为0,开始TimeKeeper的与TwoPlayer启动按钮,并获得计数器的值,只要它小于或等于0.
这里的想法是,我在窗口中创建了一个“时钟”,它显示了从几分钟后开始的时间值以及秒格式。
您能否澄清一下您的问题? – BRasmussen
哦!抱歉,问题在于我没有收到任何错误,但计时器未被添加到框架中 – CodeBoy
您的代码中存在错误,导致我们无法复制并粘贴它并运行它。如果你可以将代码合并成一个有效的[mcve],并且让我们省去尝试调试一堆错误的麻烦,那更好。 –