62,568
社区成员




import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameTimer extends JFrame implements MouseListener {
JPanel contentPane;
JLabel clockLbl;
BorderLayout borderLayout1 = new BorderLayout();
long seconds = 0l;
java.util.Timer timer = null;
boolean isRunning = false;
// Construct the frame
public FrameTimer() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
// Component initialization
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(100, 100));
this.setTitle("Frame Timer");
clockLbl = new JLabel();
contentPane.add(clockLbl, BorderLayout.CENTER);
this.addMouseListener(this);
showClock();
}
// Overridden so we can exit when window is closed
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
}
}
private void showClock() {
long tHours = seconds / 60 / 60;
long tMintus = (seconds % (60 * 60)) / 60;
long tSecons = (seconds % (60 * 60)) % 60;
String clockText = (tHours > 10 ? "" + tHours : "0" + tHours) + ":"
+ (tMintus > 10 ? "" + tMintus : "0" + tMintus) + ":"
+ (tSecons > 10 ? "" + tSecons : "0" + tSecons);
clockLbl.setText(clockText);
}
private void clock() {
seconds++;
showClock();
}
public static void main(String[] args) {
(new FrameTimer()).setVisible(true);
}
static class Job extends java.util.TimerTask {
FrameTimer timer;
public Job(FrameTimer timer) {
this.timer = timer;
}
@Override
public void run() {
timer.clock();
}
}
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
if (seconds == 0) {
timer = new java.util.Timer();
timer.schedule(new Job(this), 0, 1000);
isRunning = true;
} else if (isRunning) {
isRunning = false;
timer.cancel();
} else {
timer = null;
seconds = 0;
showClock();
}
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}