⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 timerframe.java

📁 java课程的资料以及实验的代码
💻 JAVA
字号:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class TimerFrame extends JFrame
{
	JLabel lblMsg,lblTimer;
	int timePassed;
	JButton btnStart,btnStop;

	Timer timer;//计时器
	JPanel p1;
	
	public TimerFrame()
	{
		super("Timer");
		p1 = new JPanel();
		lblMsg = new JLabel("Time Passed:");
		lblTimer = new JLabel("");

		btnStart = new JButton("Start");
		btnStart.addActionListener
		(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					timer.start();
				}
			}
		);
		btnStop = new JButton("Stop");
		btnStop.addActionListener
		(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					timer.stop();
					timePassed = 0;
				}
			}
		);
		
		//1表示每隔1毫秒触发一次,new TimerListener()是注册的监听器
		timer = new Timer
		(
			1,
			new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					timePassed++;
					lblTimer.setText(Integer.toString(timePassed));
					if(timePassed%2==0)
					{
						btnStart.setBackground(Color.cyan);	
					}
					else
						btnStart.setBackground(Color.pink);	
				}	
			}
		);
		
		p1.add(lblMsg);
		p1.add(lblTimer);
		p1.add(btnStart);
		p1.add(btnStop);
		this.getContentPane().add(p1);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setSize(500,200);
		this.setVisible(true);
	}
	//StartListener监听器
	/*class StartListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			timer.start();//启动timer
		}	
	}*/
	//StopListener监听器
	/*class StopListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			timer.stop();//停止timer
			timePassed = 0;
		}	
	}	*/
	//TimerListener监听器
	/*class TimerListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			timePassed++;
			lblTimer.setText(Integer.toString(timePassed));
			if(timePassed%2==0)
			{
				btnStart.setBackground(Color.cyan);	
			}
			else
				btnStart.setBackground(Color.pink);	
		}	
	}	*/
	//主函数
	public static void main(String[] args)
	{
		new TimerFrame();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -