日期:2014-05-20 浏览次数:20789 次
public void mouseClicked(MouseEvent evt) { Object source = e.getSource(); if (source == jButton1 && jButton1.getEnabled()) { jButton1.setEnabled(false); final javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener(){ int num = 10; public void actionPerformed(ActionEvent e) { jButton1.setText(num+""); num--; if (num == 0) { t.stop(); jButton1.setEnabled(true); } } }); t.start(); } }
------解决方案--------------------
对于SWING当中的定时器,JDK提供了javax.swing.Timer这个类,下面贴一个完整的Demo,你可以借鉴一下
import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * javax.swing.Timer的一个实例 * @author ioe_gaoyong * */ public class NumberDemo extends JFrame{ private int number=10;//初始值为10 private JButton numBtn; private Timer timer; private class NumListener implements ActionListener{ @Override public void actionPerformed(ActionEvent event) { // TODO Auto-generated method stub numBtn.setText(number+""); number--; if (number == 0) { numBtn.setText("stop"); timer.stop(); numBtn.setEnabled(true); } } } public NumberDemo(String title){ super(title); numBtn=new JButton("Click"); numBtn.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub Object source = e.getSource(); if (source == numBtn && numBtn.isEnabled()) { numBtn.setEnabled(false); timer=new Timer(1000,new NumListener()); timer.start(); } } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); this.add(numBtn); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args){ new NumberDemo("NumberDemo"); } }
------解决方案--------------------
顶楼上,用Timer