【一】需求
查询学生信息:
已知stu.txt中有一些的学生信息。
根据学生ID号查询学生信息
【二】代码
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
class Student
{
private String name;
private int age;
Student(String name,int age){
this.name=name;
this.age=age;
}
public String toString(){
return name+"--"+age;
}
}
class SearchStudent
{
private Frame f;
private TextField tf;
private Button but;
private TextArea ta;
private Dialog d;
private Label l;
private Button b;
private Map<String,Student> stu;
SearchStudent(){
init();
}
private void init(){
f=new Frame("学生信息");
tf=new TextField(60);
but=new Button("查询");
ta=new TextArea(12,70);//制定行数列数
f.setBounds(100,200,600,300);
f.setLayout(new FlowLayout());
f.add(tf);
f.add(but);
f.add(ta);
f.setVisible(true);
d=new Dialog(f,"提示信息",true);
l=new Label();
//"输入格式不对(学生学号格式为"001")或该学生信息不存在"
b=new Button("确定");
d.setBounds(110,220,500,250);
d.add(l);
d.add(b);
d.setLayout(new FlowLayout());
myEvent();
}
private void infor(){
stu=new TreeMap<String,Student>();
stu.put("001",new Student("zhangsan",12));
stu.put("004",new Student("wangwu",11));
stu.put("006",new Student("zhaoliu",22));
stu.put("101",new Student("qianbaobao",23));
stu.put("021",new Student("zhuxiao",14));
}
private void myEvent(){
infor();
//点击X号退出
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
//敲击回车键查询
tf.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
int code=e.getKeyCode();
if(code==KeyEvent.VK_ENTER){
show();
}
}
});
//点击按钮查询
but.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
show();
}
});
//点击对话框的X,对话框消失。
d.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
d.setVisible(false);
}
});
//点击确定按钮,对话框消失。
b.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
d.setVisible(false);
}
});
}
private void show(){
ta.setText("");
String select=tf.getText();
if(stu.containsKey(select)){
ta.append("学生信息:"+stu.get(select));
}else{
l.setText(select+"不存在,请重新输入!");
d.setVisible(true);
}
}
public static void main(String[] args)
{
new SearchStudent();
}
}
【三】截图
学生信息存在:
学生信息不存在: