swing入门篇 3.按钮时间处理

该博客展示了如何在Java Swing环境中创建一个简单的GUI应用程序,该程序包含一个按钮,当点击按钮时,会显示当前时间。通过实现ActionListener接口,作者创建了一个监听器,使得按钮点击事件触发时间显示更新。程序利用了SimpleDateFormat和Date类来格式化并显示时间。
摘要由CSDN通过智能技术生成
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JLabel;

public class MyFrame extends JFrame
{
	JLabel timeLabel = new JLabel("00:00:00");
	JButton button = new JButton("显示时间");
	
	public MyFrame(String title)
	{
		super(title);
		
		// 内容面板 (ContentPane)
		Container contentPane = getContentPane();
		contentPane.setLayout(new FlowLayout());
		
		// 向内容面板里添加控件
		contentPane.add(button);
		contentPane.add(timeLabel);		
		
		// 创建监听器对象
		MyButtonListener listener = new MyButtonListener();
		
		// 把监听器注册给按钮
		button.addActionListener( listener );
	}
	
	//显示时间
	public void showTime()
	{
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		String timestr = sdf.format(new Date());
		timeLabel.setText( timestr );
	}
	
	// ActionListener 是一个 interface(接口)
	private class MyButtonListener implements ActionListener
	{

		@Override
		public void actionPerformed(ActionEvent e)
		{
			// 当按钮被点击时,Swing框架会调用监听器 actionPerformed()方法
			System.out.println("按钮被点击...");
			
			MyFrame.this.showTime();
		}		
	}
}

简化版(匿名内部类)

package my;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JLabel;

public class MyFrame extends JFrame
{
	JLabel timeLabel = new JLabel("00:00:00");
	JButton button = new JButton("显示时间");
	
	public MyFrame(String title)
	{
		super(title);
		
		// 内容面板 (ContentPane)
		Container contentPane = getContentPane();
		contentPane.setLayout(new FlowLayout());
		
		// 向内容面板里添加控件
		contentPane.add(button);
		contentPane.add(timeLabel);		
		
		// 创建监听器对象
		button.addActionListener( new ActionListener(){
		@Override
		public void actionPerformed(ActionEvent e)
		{
			MyFrame.this.showTime();
		}		
	} );
	}
	
	//显示时间
	public void showTime()
	{
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		String timestr = sdf.format(new Date());
		timeLabel.setText( timestr );
	}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值