本案例包含两个java类
实现功能为:用户在三个文本框输入内容,限定用户在每个文本框只能输入6个字符(KeyListener实现),点击“确定”后,后台拼接字符判断是否匹配。使用FocusEvent焦点事件和KeyEvent键盘事件,输入序列号。判断序列号是否正确,通过对话框输出判断结果。
test6_1_programm
public class test6_1_programm {
public static void main(String[] args) {
Sequence_window window=new Sequence_window();
window.setTitle("输入序列号");
window.setBounds(10,10,460,360);
}
}
Sequence_window
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Sequence_window extends JFrame implements KeyListener, FocusListener, ActionListener{
JTextField text[]=new JTextField[3];
JButton b;
Sequence_window(){
setLayout(new FlowLayout());
//给每一个文本框添加焦点与键盘事件
for(int i=0;i<3;i++){
text[i]=new JTextField(7);
//添加键盘事件监视器
text[i].addKeyListener(this);
//处理事件时,程序检查文本框光标的位置
text[i].addFocusListener(this);
add(text[i]);
}
b=new JButton("确定");
b.addActionListener(this);//按钮添加监视器
add(b);
text[0].requestFocusInWindow();//使第一个文本框获得输入焦点
//窗口基本设置
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//重写KeyListener监视器的方法
public void keyPressed(KeyEvent e){
JTextField t=(JTextField)e.getSource();
if(t.getCaretPosition()>=5){
t.transferFocus();
}
}
public void keyTyped(KeyEvent e){};
public void keyReleased(KeyEvent e){};
//重写FocusListener监视器的方法
public void focusGained(FocusEvent e){
JTextField text=(JTextField)e.getSource();
text.setText(null);
}
public void focusLost(FocusEvent e){};
//重写ActionListener监视器的方法
public void actionPerformed(ActionEvent e){
String answer01="456789";
String answer02="abcdef";
String answer03="zhdzhd";
System.out.println(text[1].getText());
if(text[0].getText().trim().equals(answer01)&&text[1].getText().trim().equals(answer02)&&text[2].getText().trim().equals(answer03)){
JOptionPane.showMessageDialog(this,"恭喜您,您输入的软件序列号正确!","消息对话框",JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(this,"您输入的软件序列号不正确,请重新输入!","消息对话框",JOptionPane.ERROR_MESSAGE);
}
}
}
一些函数的解释:
getCaretPosition()
返回文本插入符(光标)的位置。插入符的位置被限制在 0 和文本最后一个字符(包括)之间。如果没有设置文本或插入符,则默认插入符的位置为 0。
getSource()
就是获得你目前这个事件的事件源,说通俗点,比如有一个按钮事件,你点击一个按钮,在处理事件中你用e.getSource(),就是获得这个按钮,你可以这样写
JButton a=(JButton)e.getSource();把事件源转换成你点击的那个对象类。这样你的a就可以用JButton里面的变量与方法了。
如果你有许多控件事件,这样写还可以区分你获得的是哪个控件事件的事件源。
本例是在监视器中处理事件时,产生KeyEvent e 然后通过getSource获取当前的文本框
transferFocus()
将焦点转移到下一个组件,就好像此组件曾是焦点所有者。
JTextField t = (JTextField) e.getSource(); // 文本框获取事件源 t.transferFocus(); // 等同于 transferFocus(false); 转移焦点
focusGained()
为FocusListener焦点事件监视器的成员方法,指获取焦点