JAVA程序设计(12.1)---- JFrame 监听器使用 内部类 匿名内部类 接口

要用窗口都直接继承JFrame  为了使用监听器 可以选择 

1使用内部类 内部类有监听器接口 2 主类直接加监听器接口 3匿名内部类 直接实现

package com.lovo;
/**
 * 内部类
 */
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class MyFrame6 extends JFrame {
	private JLabel lbl = new JLabel("Hello,world!");		
	private JButton stopButton = new JButton("停止");
	private JButton flashButton = new JButton("闪烁");
	private Timer timer = null;
	
	public class MyListenner implements ActionListener{<span style="white-space:pre">	</span>//创建一个拥有监听器接口的内部类
		@Override
		public void actionPerformed(ActionEvent e) {
			Object obj = e.getSource();<span style="white-space:pre">		</span>//获得信号来源
			if(obj == stopButton){
				timer.stop();
			}else if(obj == flashButton){
				timer.start();
			}else if(obj == timer){
				lbl.setVisible(!lbl.isVisible());
			}
		}
	}
	
	public MyFrame6(){
		this.setSize(600 , 400);
		this.setResizable(false);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setLayout(null);
		lbl.setBounds(150, 100, 300, 70);<span style="white-space:pre">			</span>//这一堆都是构造窗口的
		lbl.setFont(new Font("Consolas",Font.BOLD,42));
		

		MyListenner l = new MyListenner();<span style="white-space:pre">		</span>//使用监听器
		timer = new Timer(100, l);			//已经实施了一次监听,之后再添加监听 就动作了2次
		stopButton.addActionListener(l);
		flashButton.addActionListener(l);

		stopButton.setBounds(300, 300, 75, 50);
		flashButton.setBounds(200, 300, 75, 50);
		this.add(flashButton);
		this.add(stopButton);
		this.add(lbl);

	}
	
	public static void main(String[] args) {<span style="white-space:pre">			</span>//main方法  窗口可见
		new MyFrame6().setVisible(true);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值