事件:Timer的使用

import  javax.swing. * ;
import  java.awt.event. * ;
public   class  TimerFrame  extends  JFrame {
    
    JLabel labelMessage,labelTimer;
    
int timePassed;
    JButton buttonStart,buttonStop;
    Timer timer;
    JPanel panel;
    
    
public TimerFrame(){
        
super("timer");
        panel
=new JPanel();
        labelMessage
=new JLabel("timer passed");
        labelTimer
=new JLabel();
        buttonStart
=new JButton("start");
        buttonStart.addActionListener(
new StartListener());
        buttonStop
=new JButton("stop");
        buttonStop.addActionListener(
new StopListener());
        timer
=new Timer(1,new TimerListener());
        
        getContentPane().add(panel);
        panel.add(labelMessage);
        panel.add(labelTimer);
        panel.add(buttonStart);
        panel.add(buttonStop);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(
true);
        setSize(
500,200);
    }

    
public static void main(String args[]){
        
new TimerFrame();
    }

    
    
class StartListener implements ActionListener{
        
public void actionPerformed(ActionEvent e){
            timer.start();
        }

    }

    
class StopListener implements ActionListener{
        
public void actionPerformed(ActionEvent e){
            timer.stop();
        }

    }

    
class TimerListener implements ActionListener{
        
public void actionPerformed(ActionEvent e){
            timePassed
++;
            labelTimer.setText(String.valueOf(timePassed));
        }

    }

    
    
}
 

你可能感兴趣的:(事件:Timer的使用)