1.实现所示用户界面
2.在三个文本框中输入,单击“保存”按钮时,将所有输入的信息保存到当前目录下名为me.txt的文件中。
3.单击“另存为”按钮时弹出保存对话框,可以自定义文件名、保存目录。
package Work1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.ActionListener;
import java.io.*;
public class win extends JFrame {//implements ActionListener
private BorderLayout bs;
JPanel jp=new JPanel();
JLabel wlstclass = new JLabel("班级");
JTextField wtstclass =new JTextField();
JLabel wlstnum = new JLabel("学号");
JTextField wtstnum = new JTextField();
JLabel wlstname = new JLabel("姓名");
JTextField wtstname = new JTextField();
Button wbsave = new Button("保存");
Button wosave = new Button("另存为");
public win(String s){
super(s);
this.setLayout(null);
wlstclass.setBounds(new Rectangle(20,20,50,30));
wtstclass.setBounds(new Rectangle(80,20,180,30));
wlstnum.setBounds(new Rectangle(20,60,50,30));
wtstnum.setBounds(new Rectangle(80,60,180,30));
wlstname.setBounds(new Rectangle(20,100,50,30));
wtstname.setBounds(new Rectangle(80,100,180,30));
wbsave.setBounds(new Rectangle(0,140,300,20));
wosave.setBounds(new Rectangle(0,160,300,20));
this.add(wlstclass);
this.add(wtstclass);
this.add(wlstnum);
this.add(wtstnum);
this.add(wlstname);
this.add(wtstname);
this.add(wbsave);
this.add(wosave);
SimpleListener ourListener = new SimpleListener();
// 建立一个actionlistener让多个个按钮共享
wbsave.addActionListener(ourListener);
wosave.addActionListener(ourListener);
this.setSize(300,220);
this.setVisible(true);
}
public static void main(String[] args){
win w1 = new win("图形界面");
w1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class SimpleListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String buttonName = e.getActionCommand();
if (buttonName.equals("保存")) {
try {
String c = wtstclass.getText();
String name = wtstname.getText();
String num = wtstnum.getText();
String all = "班级:" +c+"学号:"+num+ "姓名:"+name+"\r\n";
File file = new File("d:/me.txt");
// 创建文件
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// 向文件写入内容
writer.write(all);
writer.flush();
writer.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(buttonName.contentEquals("另存为")) {
try {
String c = wtstclass.getText();
String name = wtstname.getText();
String num = wtstnum.getText();
String all = "班级:" +c+"学号:"+num+ "姓名:"+name+"\r\n";
String path="";
JFileChooser oths = new JFileChooser();
//oths.setSize(300,100);
oths.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
oths.showSaveDialog(jp);
path = oths.getSelectedFile().getAbsolutePath();
FileWriter writer=new FileWriter(path+".txt");
// 向文件写入内容
writer.write(all);
writer.flush();
writer.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
Comments | NOTHING