计时器功能中鼠标点击的问题

dolaqu 2010-04-16 02:30:15
在设计一个计时器功能控件的时候,鼠标单击一次开始计时,再次单击鼠标一次结束,显示出计时结果。然后再单击鼠标一次,计时重新开始,再次单击第二次计时结束。我使用MOUSE_CLICKED来完成。但是怎么控制 单击鼠标后 是运行计时开始呢,还是运行计时结束呢?这个该怎么控制?我是想用个0 1 循环来控制。可不知道该怎么统计单击鼠标的次数。
JDK中有个这样的方法 public int getClickCount()
但是不知道怎么使用。求大侠们帮忙!
...全文
122 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
dolaqu 2010-04-17
  • 打赏
  • 举报
回复
谢谢!
hq1305018 2010-04-16
  • 打赏
  • 举报
回复
我做了一个,你参考一下。

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) {
}
}

62,624

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧