問題是我沒有得到任何錯誤,但計時器沒有被添加到框架。反覆「越來越」變化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],並且讓我們省去嘗試調試一堆錯誤的麻煩,那更好。 –