,实现下列要求:
1 录入学生信息(学号、性别、年龄、党否、系别、简历);确认后将信息保存
2 菜单条
查询:输入学号,显示其信息
退出:询问并确认后退出系统
3 工具条:对应菜单中的退出功能,并设置提示信息
状态条:显示作者、日期、当前时间
这是最近的一次JAVA实验题目,为了巩固一下知识,所以写出来。
我设计的界面:
我用的是“新建”->“Java桌面应用程序”...,NetBeans会自动生成一些类,如StuInfoAboutBox.java,StuInfoApp.java,
StuInfoView.java,StuInfoAboutBox.java就是一个关于对话框,StuInfoApp.java是主程序用于启动程序的类,
StuInfoView.java是视图类,就是对界面设计的类。
设计:当输入完毕点击“录入”按钮时,询问并确认后实现信息的录入,并在当前目录下生成一个“学生信息.txt”的文档。
存储形式如下(实现后截图):
这是代码编写的困难的部分,花了偶好长的时间!
其实实验的主要代码就是在两个按钮的事件响应上。
详细设计: 1.第一步就是界面的设计,一步步的把需要的组件添加到框架上。修改一下系统生成的菜单按要求,添加工具栏(JToolbar组件),其
中添加几个按钮,按自己的要求。在StatusPanel上,可以将不需要的组件删除,添加我们需要的组件。
需要添加的组建类:JLabel--标签,JTextFiled--文本字段,JButton--按钮,JRadioButton--单选按钮,ButtonGroup--按钮组
将RadioButton组合,使其只能有一个可选。JComboBox--组合框,Ugg boots,年龄的选择,JTextArea--文本区域,简历的录入。
2. 接下来就是规划一下具体代码的编写了。
首先我新建了一个类用于存储学生信息
package studentinfo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Administrator
*/
public class Info {
int m_nStuID;
String m_strStuName;
String m_strStuSex;
int m_nStuAge;
String m_strIsPartyMember;
String m_strDept;
String m_strResume;
static int flag = 0;
private long beforePointer;//读一行前文件的指针
private long afterPointer;//读一行后文件的指针
File file;
RandomAccessFile raf;
Info() {}//无参构造函数
//根据学号建立一个对象
Info(int StuID) throws FileNotFoundException {
this.m_nStuID = StuID;
String parentpath = ".";
String childpath = "学生信息";
String txt = ".txt";
file = new File(parentpath, childpath + txt);
raf = new RandomAccessFile(file, "rw");//根据学号建立一个对象
}
//根据学生信息构造一个对象
Info(int StuID, String StuName, String StuSex, int StuAge,
String IsPartyMember, String Dept, String Resume) throws FileNotFoundException {
this.m_nStuID = StuID;
this.m_strStuName = StuName;
this.m_strStuSex = StuSex;
this.m_nStuAge = StuAge;
this.m_strIsPartyMember = IsPartyMember;
this.m_strDept = Dept;
this.m_strResume = Resume;
String parentpath = ".";
String childpath = "学生信息";
String txt = ".txt";
file = new File(parentpath, childpath + txt);
if (file.exists() && flag == 0) {//每次运行程序前检查,如果存在''学生信息.txt"文件,就将它删除
file.delete();
}
flag++;
raf = new RandomAccessFile(file, "rw");//将文件包装成RandomAccessFile
}
public void SaveStuInfo() throws FileNotFoundException, IOException {
raf.seek(raf.length());//将文件指针移动到文件末尾,即每添加一个学生信息,都是在末尾添加的
raf.write("学号:".getBytes());//此处必须加上String的getBytes()方法,否则打开后看到的将是乱
//码。这是由RandomAccessFile类的字节流的write() 写入方式决定的
raf.write(String.valueOf(m_nStuID).getBytes());//将整型包装成String写入
raf.write("/r/n".getBytes());//写入换行符
raf.write("姓名:".getBytes());
raf.write(m_strStuName.getBytes());
raf.write("/r/n".getBytes());
raf.write("性别:".getBytes());
raf.write(m_strStuSex.getBytes());
raf.write("/r/n".getBytes());
raf.write("年龄:".getBytes());
raf.write(String.valueOf(m_nStuAge).getBytes());
raf.write("/r/n".getBytes());
raf.write("党否:".getBytes());
raf.write(m_strIsPartyMember.getBytes());
raf.write("/r/n".getBytes());
raf.write("系别:".getBytes());
raf.write(m_strDept.getBytes());
raf.write("/r/n".getBytes());
raf.write("简历:".getBytes());
raf.write(m_strResume.getBytes());
raf.write("/r/n".getBytes());
raf.write("---------".getBytes());
raf.write("/r/n".getBytes());
raf.close();//为了安全,cheap UGG boots,关闭文件
}
//将读入一行后的信息包装成String,RandomAccessFile的readLine()方法虽然返回的是String,但是有点问题
//必须转换一下
public String toChString1(String str) throws IOException {
// long beforPointer = raf.getFilePointer();
// str = raf.readLine();
int length = (int) (afterPointer - beforePointer); //获得读入一行前,后所读信息的长度
byte[] strbyte = new byte[length];
raf.seek(beforePointer); //文件指针移动到读入一行前位置
raf.read(strbyte); //将读入信息存入字节数组
String newString = new String(strbyte); //重新包装成String
return newString;
}
public Info SearchStuInfo() throws IOException { //查找信息
Info info = new Info(); //构造对象
int sign = 0; //是否找到标志位
String str;
// System.out.println(raf.length());
// System.out.println(":".getBytes().length);
while (raf.getFilePointer() < raf.length()) { //如果没到文件结尾,继续查找
beforePointer = raf.getFilePointer(); //读入前文件指针
str = raf.readLine(); //读入一行
afterPointer = raf.getFilePointer(); //读入后指针
String newString = toChString1(str); //转换
if (newString.substring(0, 3).equals("学号:")) { //如果找到“学号:”
raf.seek(beforePointer + "学号:".getBytes().length); //文件指针移动到“学号:”后,读入信息
String s = raf.readLine(); //读入信息
if (s.equals(String.valueOf(m_nStuID))) { //如果找到学号
raf.seek(raf.getFilePointer() + (long) "姓名:".getBytes().length); //读入信息
beforePointer = raf.getFilePointer();
str = raf.readLine();
afterPointer = raf.getFilePointer();
info.m_strStuName = toChString1(str); //赋值给新创建的对象
raf.seek(raf.getFilePointer() + (long) "性别:".getBytes().length);
beforePointer = raf.getFilePointer();
str = raf.readLine();
afterPointer = raf.getFilePointer();
info.m_strStuSex = toChString1(str);
raf.seek(raf.getFilePointer() + (long) "年龄:".getBytes().length);
info.m_nStuAge = Integer.parseInt(raf.readLine());
raf.seek(raf.getFilePointer() + (long) "党否:".getBytes().length);
beforePointer = raf.getFilePointer();
str = raf.readLine();
afterPointer = raf.getFilePointer();
info.m_strIsPartyMember = toChString1(str);
raf.seek(raf.getFilePointer() + (long) "系别:".getBytes().length);
beforePointer = raf.getFilePointer();
str = raf.readLine();
afterPointer = raf.getFilePointer();
info.m_strDept = toChString1(str);
long temppointer = raf.getFilePointer() + (long) "简历:".getBytes().length; //简历不止一行,获取“简历:”后的指针
raf.seek(temppointer);
while (afterPointer < raf.length()) { //如果没到文件尾
beforePointer = raf.getFilePointer();
str = raf.readLine();
afterPointer = raf.getFilePointer();
String tempString = toChString1(str);
if (tempString.equals("---------/r/n")) { //这个学生是否读完
byte[] b = new byte[(int) beforePointer - (int) temppointer]; //读入所有简历信息
raf.seek(temppointer);
raf.read(b);
info.m_strResume = new String(b);
sign = 1; //找到
raf.close();
break;
}
}
}
}
if (sign == 1) { //找到退出循环
break;
}
}
if(sign == 0) //没找到对象为空
info = null;
return info;
}
}
这段代码是最难写的了。注释很清楚。不详细说了
2.//StuInfoView.java
package studentinfo;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
* The application's main frame.
*/
public class StudentInfoView extends FrameView {
private int StuID;
private String StuName;
private String StuSex;
private String IsPartyMember;
private int StuAge;
private String Dept;
private String Resume;
private Timer mytimer;
public StudentInfoView(SingleFrameApplication app) {
super(app);
initComponents();
// 自己添加的代码
date.setText(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.get Instance().getTime())); //设置日期
int delay = 1000; //延时
mytimer = new Timer(delay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String t = new SimpleDateFormat("HH:mm:ss").format(Calendar.getIn stance().getTime());
time.setText(t);
}
}); //动态显示时间
mytimer.start(); //开启计时器
menusearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stusearchActionPerformed(evt);
}
}); //菜单栏查找菜单项的事件响应
toolsearch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stusearchActionPerformed(evt);
}
}); //工具栏查找按钮的事件响应
toolexit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
}); //菜单栏退出按钮的事件响应
//------------------------------------------------ -------------系统自动添加的代码(略)--------------------------------
private void stuenterActionPerformed(java.awt.event.ActionEvent evt) { //录入按钮的事件响应
if (JOptionPane.YES_OPTION != JOptionPane.showConfirmDialog(mainPanel, "确定录入吗?", "消息", JOptionPane.YES_NO_OPTION)) {
return; //未确定则返回
}
try {
StuID = Integer.parseInt(stuid.getText());
} catch (NumberFormatException numberFormatException) { //格式不匹配将焦点置于学号上
JOptionPane.showMessageDialog(mainPanel, "学号未输入或者学号格式不匹配!");
stuid.requestFocusInWindow();
stuid.selectAll();
return;
}
StuName = stuname.getText();
if (stuboy.isSelected()) { //如果男选择,则。。
StuSex = "男";
} else {
StuSex = "女";
}
StuAge = Integer.parseInt(stuage.getSelectedItem().toString ());
if (stuisparty.isSelected()) {
IsPartyMember = "是";
} else {
IsPartyMember = "否";
}
Dept = studept.getSelectedItem().toString();
Resume = sturesume.getText();
try { //构造新的学生对象并调用存储方法
new Info(StuID, StuName, StuSex, StuAge, IsPartyMember, Dept, Resume).SaveStuInfo();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(mainPanel, ex.getMessage());
} catch (IOException ex) {
JOptionPane.showMessageDialog(mainPanel, ex.getMessage());
}
JOptionPane.showMessageDialog(mainPanel, "录入成功!");
}
private void stusearchActionPerformed(java.awt.event.ActionEven t evt) {
int stuID = 0; //查找学生信息,并设置相关组件显示信息
try {
stuID = Integer.parseInt(stuid.getText());
} catch (NumberFormatException numberFormatException) {
JOptionPane.showMessageDialog(mainPanel, "学号未输入或者格式不匹配!");
stuid.requestFocusInWindow();
stuid.selectAll();
return;
}
try {
Info info = new Info(stuID).SearchStuInfo();
if (info == null) {
JOptionPane.showMessageDialog(mainPanel, "不存在该学号的同学!");
return;
}
stuname.setText(info.m_strStuName);
if (info.m_strStuSex.equals("男/r/n")) {
stuboy.setSelected(true);
} else {
stugirl.setSelected(true);
}
stuage.setSelectedIndex(info.m_nStuAge - 18);
if (info.m_strIsPartyMember.equals("是/r/n")) {
stuisparty.setSelected(true);
} else {
stunotparty.setSelected(true);
}
studept.setSelectedItem(info.m_strDept);
sturesume.setText(info.m_strResume);
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(mainPanel, ex.getMessage());
} catch (IOException ex) {
JOptionPane.showMessageDialog(mainPanel, ex.getMessage());
}
}
private void toolaboutActionPerformed(java.awt.event.ActionEven t evt) {
showAboutBox();
}
private void exitActionPerformed(java.awt.event.ActionEvent evt) { //退出按钮的相应
if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(mainPanel, "确定要退出吗?", "消息", JOptionPane.YES_NO_OPTION)) {
System.exit(0);
} else {
return;
}
}
// -------------------------------------------------- -----系统添加代码(略)----------------------------------------
3.//StuInfoApp.java
package studentinfo;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
/**
* The main class of the application.
*/
public class StudentInfoApp extends SingleFrameApplication {
/**
* At startup create and show the main frame of the application.
*/
@Override
protected void startup() { //设置点击右上方叉关闭时的相应
JFrame frame = new StudentInfoView(this).getFrame();
frame.addWindowListener(new MainFrameListener()); //添加框架事件响应
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_O N_CLOSE); //这个必须有
frame.pack();
frame.setVisible(true);
//show(new StudentInfoView(this)); //这是系统的代码,注释掉
}
private class MainFrameListener extends WindowAdapter { //系统的关闭时事件响应事件
@Override
public void windowClosing(WindowEvent e) {
if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(StudentInfoApp.getAp plication().getMainFrame(), "确定退出吗?", "消息", JOptionPane.YES_NO_CANCEL_OPTION)) {
System.exit(0);
} else {
return;
}
}
}
/**
* This method is to initialize the specified window by injecting resources.
* Windows shown in our application come fully initialized from the GUI
* builder, so this additional configuration is not needed.
*/
@Override
protected void configureWindow(java.awt.Window root) {
}
/**
* A convenient static getter for the application instance.
* @return the instance of StudentInfoApp
*/
public static StudentInfoApp getApplication() {
return Application.getInstance(StudentInfoApp.class);
}
/**
* Main method launching the application.
*/
public static void main(String[] args) {
launch(StudentInfoApp.class,UGG boots cheap, args);
}
}
//---------------------------------------
--------- -----------------结束------------------------