要用窗口都直接继承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);
}
}