我的程序是要实现一个从输入界面输入用户信息,然后写入一个文件当中,再从文件中读出来.我写的这个程序,编译执行就没问题,当我点击用户界面的"确定"后就出现了错误,哪位帮忙解决一下哈.先谢谢了!!!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class lab3 implements ActionListener,ItemListener
{
JFrame f=null;
JTextField name,num,age;
JRadioButton r1,r2;
int op=0;
String sex1;
public lab3(){
JFrame f = new JFrame("学生信息输入表");
Container contentPane = f.getContentPane();
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3, 2));
JLabel L1 = new JLabel("姓名:");
JTextField name = new JTextField();
JLabel L2 = new JLabel("学号:");
JTextField num = new JTextField();
JLabel L4 = new JLabel("年龄:");
JTextField age = new JTextField();
p1.add(L1);
p1.add(name);
p1.add(L2);
p1.add(num);
p1.add(L4);
p1.add(age);
contentPane.add(p1, BorderLayout.NORTH);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(1, 2));
JLabel L3 = new JLabel("性别:");
r1=new JRadioButton("男");
r2=new JRadioButton("女");
p3.add(L3);
p3.add(r1);
p3.add(r2);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
r1.addItemListener(this);
r2.addItemListener(this);
contentPane.add(p3, BorderLayout.CENTER);
JPanel p2 = new JPanel();
p2.setLayout(new GridLayout(1, 2));
JButton b1 = new JButton("确定");
JButton b2 = new JButton("取消");
p2.add(b1);
p2.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
contentPane.add(p2, BorderLayout.SOUTH);
f.setSize(210, 200);
//f.pack();//对组件进行排列
f.show();//显示
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent e){//单选按钮被单击时触发
if(e.getSource()==r1)op=1;
if(e.getSource()==r2)op=2;
}
public void actionPerformed(ActionEvent e){//确定,取消按钮被单击时触发
String cmd=e.getActionCommand();
if(cmd.equals("确定")){
String name1=name.getText();
System.out.println(name1);
int number=Integer.parseInt(num.getText());
int age1=Integer.parseInt(age.getText());
switch(op){
case 1:
sex1="男";
break;
case 2:
sex1="女";
break;
}
//写文件
String filename="F:\\students.txt";
try{
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write(name1);
out.newLine();
out.write(number);
out.newLine();
out.write(sex1);
out.newLine();
out.write(age1);
out.newLine();
out.close();
}
catch (IOException iox)
{
System.out.println("写文件有错误!"+filename);
}
//读文件
String filename2 ="F:\\students.txt";
String line;
try{
BufferedReader in =new BufferedReader(new FileReader(filename2));
line=in.readLine();
while (line !=null)
{
System.out.println(line);
line=in.readLine();
}
in.close();
}
catch (IOException iox)
{
System.out.println("读文件有错误!"+filename2);
}
f.setVisible(false);
return;
}
else if(cmd.equals("取消"))System.exit(0);
}
public static void main(String args[])
{
new lab3();
}
}