Java--第15周实验--

public class Example10_9 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileWindows win = new FileWindows();
	}

}


 

import java.awt.BorderLayout;
import java.awt.FileDialog;
import java.awt.event.*;

import javax.swing.*;

import java.io.*;


public class FileWindows extends JFrame implements ActionListener{
	JFileChooser fileDialog_save,fileDialog_load;// 声明两个文件对话框
	JMenuBar menubar;
	JMenu menu;
	JMenuItem itemOpen ,itemSave;
	JTextArea text;
	BufferedReader in;
	FileReader file_reader;
	BufferedWriter out;
	FileWriter tofile;
	public FileWindows() {
		super("带文件对话框的窗口");
		setSize(260,270);
		setVisible(true);
		menubar = new JMenuBar();
		menu = new JMenu("选项");
		itemOpen = new JMenuItem("打开文件");
		itemSave = new JMenuItem("保存文件");
		itemOpen.addActionListener(this);
		itemSave.addActionListener(this);
		menu.add(itemOpen);
		menu.add(itemSave);
		menubar.add(menu);
		setJMenuBar(menubar);
		fileDialog_save = new JFileChooser();
		fileDialog_load = new JFileChooser();
		text = new JTextArea(10, 10);
		add(text,BorderLayout.CENTER);
	}
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==itemOpen)
		{
			fileDialog_load.setVisible(true);
			text.setText(null);
			String s; 
			
			if(fileDialog_load.showOpenDialog(null)== JFileChooser.APPROVE_OPTION)
			{				try {
					File file = fileDialog_load.getSelectedFile();
					file_reader = new FileReader(file);
					in = new BufferedReader(file_reader);
					while ((s=in.readLine())!=null) {
						text.append(s+'\n');
						in.close();
						file_reader.close();
						
					}
				} catch (IOException e2) {}
			}
		}
		else if(e.getSource()==itemSave)
		{
			fileDialog_save.setVisible(true);
			if(fileDialog_load.showOpenDialog(null)== JFileChooser.APPROVE_OPTION)
			{
				try {
					File file = fileDialog_save.getSelectedFile();
					tofile = new FileWriter(file);
					out = new BufferedWriter(tofile);
					out.write(text.getText(), 0, (text.getText()).length());
					out.close();
					tofile.close();
						
				} catch (IOException e2) {
					// TODO: handle exception
				}
			}
		}
		
	}

}


 

你可能感兴趣的:(cpp)