1、文本框使用事件
package aa.com.eum;
import java.awt.;
import java.awt.event.;
import javax.swing.*;
public class Event extends JFrame{
private JTextField tf;
private JTextField tf2;
private void initEvent() {
tf.addFocusListener(new MyListener());
}
public Event() {
init();
}
private void init() {
tf=new JTextField(10);
tf2=new JTextField(10);
this.add(tf);
this.add(tf2);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
Dimension dim=getToolkit().getScreenSize() ;//获取屏幕大小
initEvent();
int w=dim.width/2;
int h=dim.height/2;
this.setResizable(false);//不能更改窗口大小
this.setTitle("事件案例");
this.setSize(500, 300);
this.setLocation(w-500/2, h-300/2);//屏幕中心位置
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//多个文本框时用e.getComponent()方法判断是哪个文本框
//tf.requestFocus();重新获得焦点
class MyListener implements FocusListener{
//获得焦点
public void focusGained(FocusEvent e) {
System.out .println("获得焦点");
}
//失去焦点
public void focusLost(FocusEvent e) {
if(tf.getText().length()<=8){
System.out .println("密码必须大于8位");
tf.requestFocus();
}
}
}
}