实现:
界面如图几个控件:
后台文本文件:
当输入查询ID,点击“查询”,若文本文件查询到有这个ID,就输出相关所有信息,若没有,则显示“查无此人!”,点击“保存”按钮,保存显示信息文件;点击“关闭”按钮,退出对话框:
源码:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame{
//事件监听的对象要设为全局变量
JTextField jtf;
JTextArea jta;
String save="";
public Test() {
//标签、按钮
JLabel lb1 = new JLabel("请输入查询ID:");
jtf = new JTextField(20);
JButton b1 = new JButton("查询");
JButton b2 = new JButton("关闭");
JButton b3 = new JButton("保存");
jta = new JTextArea(10,30);
//监听事件注册
DataFind mm = new DataFind();
b1.addActionListener(mm);
//保存——事件注册
Data ssss = new Data();
b3.addActionListener(ssss);
//关闭按钮事件
b2.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ee){
System.exit(0);
}
});
//容器,添加
JPanel p = new JPanel();
p.add(lb1);
p.add(jtf);
p.add(b1);
p.add(b2);
p.add(jta);
getContentPane().add(p);
setSize(500,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
//事件监听
class DataFind implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str = jtf.getText();
boolean find = false;
jta.setText("");
String ss="";
try {
Scanner sc = new Scanner(new File("data.txt"));
while(sc.hasNextLine()) {
ss = sc.nextLine();
if(ss.indexOf(str)>=0) {
find = true;
break;
}
}
if(find) {
String[] aa = ss.split("\\s+");
String Disp = "学号:" + aa[0] + "\r\n姓名:" + aa[1] + "\r\n计算机:" + aa[2]
+ "\r\n外语:"+ aa[3] + "\r\n统计原理:" + aa[4];
jta.setText(Disp);
}
else JOptionPane.showMessageDialog(null,"查无此人!");
} catch (Exception e2) {
// TODO: handle exception
}
}
}
//事件监听 2 ---保存
class Data implements ActionListener{
public void actionPerformed(ActionEvent e){
try {
String save = jta.getText();
FileWriter fw = new FileWriter("js.txt");
fw.write(save);
fw.close();
}
catch (Exception ex) {
}
}
}
}