0
我正在尝试创建一个程序,作为时钟每秒钟滴答的练习。我试图找到关于这方面的信息,但是对于我所学到的或者不相关的内容来说,要么太复杂。java-创建一个时钟,而不使用内置的时钟类
我想它排序工作是这样的:
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()
类SimpleClock
本质上,它只是从上午切换到下午,因为我目前在while循环结束时切换了程序。我知道我必须改变它,但我不知道如何,因为时钟甚至不会摆在首位。
你在哪里叫剔你应该只做到这一点?你可以使用System.currentTimeMillis()吗? –
@Bálint无论何时点击GUI中的滴答按钮,它都会打勾。 – marstran
DId调试'tick'?图形用户界面不使用...主要只使用时钟,添加此代码是否有用? – AxelH