我正在尝试创建一个程序作为练习,其中时钟每秒钟滴答。我试图找到有关这方面的信息,但它对我学到的东西来说太复杂了,或者说不相关。
我希望它能像这样工作:
Clock starts at time: 12:00:00 AM
Clock has been set to time: 11:59:00 PM
TICK: 11:59:01 PM
这是我到目前为止编写的代码:
public class Clock {
public static void main(String[] args) {
SimpleClock clock = new SimpleClock();
System.out.println("Clock starts at time: " + clock.time());
clock.set(11, 59, 00, false);
System.out.println("Clock has been set to time: " + clock.time());
for (int j = 0; j < 60; j++) {
for (int i = 0; i < 60; i++) {
clock.tick();
System.out.println("TICK: " + clock.time());
}
}
System.out.println("Clock finally reads: " + clock.time());
}
}
GUI:
public class ClockView extends JFrame {
/* -----------------Private Member variables --------------------- */
private static final long serialVersionUID = 1L;
private static int ROWS_IN_GRID = 2;
private static int COLS_IN_GRID = 1;
private static int BUTTON_ROWS = 1;
private static int BUTTON_COLS = 2;
private SimpleClock clock;
private JLabel face;
/**
* Constructor. Takes a SimpleClock as an argument and builds a graphical
* interface using that clock the model. The Tick button increments the
* clock by 1 second, while the Reset button sets the clock back to midnight
* (12:00:00AM). *
*
* @param clock
* - the clock instance used to store the time for the view
*/
public ClockView(SimpleClock clock) {
super("SimpleClock Demo");
this.clock = clock;
this.face = new JLabel("<html><span style='font-size:20px'>"
+ this.clock.time() + "</span></html>");
this.setLayout(new GridLayout(ROWS_IN_GRID, COLS_IN_GRID));
this.add(this.face);
JPanel buttonPanel = new JPanel(
new GridLayout(BUTTON_ROWS, BUTTON_COLS));
JButton tickButton = new JButton("Tick");
tickButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
clock.tick();
ClockView.this.face
.setText("<html><span style='font-size:20px'>"
+ clock.time() + "</span></html>");
}
});
buttonPanel.add(tickButton);
JButton resetButton = new JButton("reset");
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clock.set(12, 0, 0, true);
ClockView.this.face
.setText("<html><span style='font-size:20px'>"
+ clock.time() + "</span></html>");
}
});
buttonPanel.add(resetButton);
this.add(buttonPanel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ClockView v = new ClockView(new SimpleClock());
}
}
我退出肯定我的逻辑错误发生在public void tick()
类<{1}}
基本上,它只是从am切换到pm,因为我目前在while循环结束时切换程序。我知道我必须移动它,但我不知道如何,因为时钟甚至不会在第一时间打勾。
答案 0 :(得分:0)
您当前的tick
方法包含大量循环,最终会以时间&gt; = 12小时结束。为什么?因为您将添加一秒,直到循环条件不满足。因此,在hours >= 12
之前,还要等到minutes = 59
或seconds = 59
你应该只添加一秒,就像评论所说:将时钟提前1秒。。 然后进行具体检查。
public void tick(){
seconds++;
if(seconds => 60){
seconds = 0;
minutes++;
if(....)
...
}
}
此外,morning
将始终在此处切换,但您应该只在小时数达到限制时执行此操作