一、事件处理
监听器机制。
1.添加一个监听器类,实现ActionListener接口
自定义窗口类MyFrame中的内部类:
import java.awt.event //ActionListener
private class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
System.out.println("、、、");
}
}
2.创建监听器对象
在MyFrame中:
MyActionListener listener = new MyActionListener();
button.addActionListener(listener);
//当button按钮被点击时,调用监听器的方法
每点一次,就会调用一次。
ActionListener是一个接口,不能直接使用,需要定义一个子类,然后实现规定的方法。
二、简化写法
//写成父类的形式
ActionListener listener = new MyActionListener();
button.addActionListener(listener);
//合并
button.addActionListener(new MyActionListener());
三、显示当前时间
把时间显示在jlabel中。
1、取得时间的方法:
import java.text
import java.sql
import java.util
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timeStr = sdf.format(new Date());
System.out.println(timeStr);
将时间打印出来
2、在界面中显示时间
添加JLabel,点击按钮时显示时间(通过监听器)
在界面(MyFrame类)中创建一个JLabel:
JLabel timeLabel = new JLabel("00:00:00");
root.add(timeLabel);
将创建的时间显示标签成MyFrame类的属性,以便内部类MyActionListener的访问;
内部类可以访问当前外部对象的属性。
private class MyActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
System.out.println("、、、");
//1.取得时间
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timeStr = sdf.format(new Date());
System.out.println(timeStr);
//2.外部添加标签控件timeLabel
//3.显示时间
timeLabel.setText(timeStr); //点击按钮时,显示时间
}
}
四、匿名内部类
监听器Listener 的三种写法:
1.内部类;2.匿名内部类;3.Lambda表达式。
匿名内部类的写法:
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.out.println("、、、");
//1.取得时间
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timeStr = sdf.format(new Date());
System.out.println(timeStr);
//2.外部添加标签控件timeLabel
//3.显示时间
timeLabel.setText(timeStr);
}
});
通常:
会加一个方法,先将内部类中需要的操作放入方法中,再在内部类中调用方法:
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.out.println("、、、");
showTime();
}
});
//方法
public void showTime(){
//1.取得时间
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String timeStr = sdf.format(new Date());
System.out.println(timeStr);
//2.外部添加标签控件timeLabel
//3.显示时间
timeLabel.setText(timeStr);
}
匿名内部类更多使用。
五、Lambda表达式
对匿名内部类的进一步简化形式。
//e是方法的参数,{}是方法体
button.addActionListener((e)->{
System.out.println("、、、");
showTime();
});
(e)里是参数,{}里是方法体。