GUI练习:根据ID查询学生信息

【一】需求

查询学生信息:
已知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();
	}
}

 【三】截图

学生信息存在:

 学生信息不存在:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值