【发布时间】:2011-04-11 09:04:08
【问题描述】:
使用下面的代码,计时器计数 4 秒,如果达到 1,
'你好世界!'打印出来。
我怎样才能使计时器计数为 4 TWICE 并打印
Hello World 仅在第一个计数 1 时。
我该怎么做?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Calendar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Toolkit;
class clockExample1 extends JFrame {
private JTextField _textfield1;
public clockExample1() {
_textfield1 = new JTextField(5);
_textfield1.setEditable(false);
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
panel1.add(_textfield1);
JButton button1 = new JButton("click here");
this.setContentPane(panel1);
this.setTitle("Text Clock 1");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(true);
panel1.add(button1);
ClockListener cl = new ClockListener();
Timer t = new Timer(1000, cl);
t.start();
}
class ClockListener implements ActionListener {
int count = 0;
public void actionPerformed(ActionEvent e) {
int fakeSecond = (count++ % 4) + 1;
if (fakeSecond == 1) { System.out.println( "Hello, World!" );
}
Calendar now = Calendar.getInstance();
int h = now.get(Calendar.HOUR_OF_DAY);
int m = now.get(Calendar.MINUTE);
int s = now.get(Calendar.SECOND);
_textfield1.setText("" + fakeSecond + "");
}
}
public static void main(String[] args) {
JFrame clock = new clockExample1();
clock.setVisible(true);
}
}
【问题讨论】:
-
你没有忘记把它标记为家庭作业吗 ;-)
-
简单是什么意思?哈哈,我是初学者!
-
定时器是你自己的对象吗?我不认为 java.util.Timer 有一个名为 start 的方法?
标签: java swing loops timer count