ITEEDU

JFileChoose,JColorChooer,JSeparator文件选择对话框,颜色选择对话框,分隔线的使用与介绍.

13-1:使用JFileChooser组件.

JFileChooser的类层次结构图:
     java.lang.Object
     --java.awt.Component
       --java.awt.Container
        --javax.swing.JComponent
         --javax.swing.JFileChooser

当我们在处理窗口上的一些操作,特别是文本处理的部份,例如一个文本编辑器上打了一段文字,我们可能希望将此段文字存储起来 ,供以后方便使用,此时系统应当提供一个存储文件的对话框,将此段文字存到一个自定义或内定的文件名中.同样,当我们要叫出某个 文件时,系统也应当提供打开文件的功能,让我们选择所欲打开的文件.在java中这些操作都可以由JFileChoose组件来达成.这个组件 提供了打开文件存盘的窗口功能,也提供了显示特定类型文件图标的功能,亦能针对某些文件类型做过滤的操作.如果你的系统需要对 某些文件或文件做操作,JFileChooser组件可以让你轻松地做出漂亮的用户界面.在这边读者要注意的是,JFileChooser本身不提供读 文件或存盘的功能,这些功能必须你自行实作.事实上,JFileChooser本身只是一个对话框模型,它也是依附在JDialog的结构上,因此 它只是一个针对文件操作的对话框,当然本身也就不会有读文件或存盘的功能!以下我们来看JFileChooser的构造函数:

JFileChooser构造函数:
  • JFileChooser():建立一个JFileChooser对象,默认的文件对话框路径是用户的家目录(Home Directory),例如在windows 2000中的 Administrator的家目录是在C:\Documents and Settings\Administrator中. JFileChooser(File currentDirectory):建立一个JFileChooser对象,并以File所在位置文件为文件对话框的打开路径.
  • JFileChooser(File currentDirectory,FileSystemView fsv):建立一个JFileChooser对象,以File所在位置为文件对话框的打开路 径并设置文件图标查看方式.
  • JFileChooser(FileSystemView fsv):建立一个JFileChooser对象,并设置文件图标查看方式.
  • JFileChooser(String currentDirectoryPath):建立一个JFileChooser对象,并设置文件对话框的打开路径.
  • JFileChooser(String currentDirectoryPath,FileSystemView fsv): 建立一个JFileChooser对象,并设置文件对话框的打开路径与 文件图标查看方式.

13-1-1:建立一个简单的JFileChooser对话框:

介绍完JFileChooser构造函数后,我们来实作一个简单的范例.这个范例可以让用户在JTextArea上输入文字,输入完后按下"存储 文件"按钮就可以打开JFileChooser存储文件对话框,用户可以输入欲存储的文件名,按下"Save"按钮就可以存储文件.若用户要打开 某个文件内容,只需要按下"打开文件"按钮,就会出现JFileChooser打开文件对话框,用户选择好所欲打开的文件就可以将数据读入 JTextArea中.

在这个范例中,我们使用JFileChooser的showOpenDialog()或showSaveDialog()方法来打开文件对话框,此两个方法在用户按下 按钮或关闭对话框时会返回一个整数值,这个整数值的类型有3种,分别是:

  • JFileChooser.CANCEL_OPTION:表示用户按下取消按钮.
  • JFileChooser.APPROVE_OPTION:表示用户按下确定按钮.
  • JFileChooser.ERROR_OPEION:表示有错误产生或是对话框不正常关闭.

利用这3个整数值我们就能判断用户到底在对话框中做了什么操作,并加以处理,例如当用户选择了文件并按下确定键后,我们就可 以利用getSelectedFile()方法取得文件对象,利用这个文件对象我们就能够取得文件名称(getName())与文件路径(getPath());

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class FileChooserDemo1 implements ActionListener {
	JFrame f = null;
	JLabel label = null;
	JTextArea textarea = null;
	JFileChooser fileChooser = null;

	public FileChooserDemo1() {
		f = new JFrame("FileChooser Example");
		Container contentPane = f.getContentPane();
		textarea = new JTextArea();
		JScrollPane scrollPane = new JScrollPane(textarea);
		scrollPane.setPreferredSize(new Dimension(350, 300));

		JPanel panel = new JPanel();
		JButton b1 = new JButton("新建文件");
		b1.addActionListener(this);
		JButton b2 = new JButton("存储文件");
		b2.addActionListener(this);
		panel.add(b1);
		panel.add(b2);

		label = new JLabel(" ", JLabel.CENTER);

		fileChooser = new JFileChooser("D:\\");// 建立一个FileChooser对象,并指定D:的目录为默认文件对话框路径.

		contentPane.add(label, BorderLayout.NORTH);
		contentPane.add(scrollPane, BorderLayout.CENTER);
		contentPane.add(panel, BorderLayout.SOUTH);

		f.pack();
		f.setVisible(true);

		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}

	public static void main(String[] args) {
		new FileChooserDemo1();
	}

	public void actionPerformed(ActionEvent e) {
		File file = null;
		int result;
		/*
		 * 当用户按下"打开文件"按钮时,JFileChooser的showOpenDialog()方法会输出文件对话框,并利用
		 * setApproveButtonText
		 * ()方法取代按钮上"Open"文字;以setDialogTitle()方法设置打开文件对话框Title名称.
		 * 当使用选择完后,会将选择结果存到result变量中.
		 */
		if (e.getActionCommand().equals("新建文件")) {
			fileChooser.setApproveButtonText("确定");
			fileChooser.setDialogTitle("打开文件");
			result = fileChooser.showOpenDialog(f);

			textarea.setText("");

			/*
			 * 当用户按下打开文件对话框的"确定"钮后,我们就可以利用getSelectedFile()方法取得文件对象.若是用户按下打
			 * 开文件对话框的"Cancel"钮,则将在label上显示"你没有选择任何文件"字样.
			 */
			if (result == JFileChooser.APPROVE_OPTION) {
				file = fileChooser.getSelectedFile();
				label.setText("您选择打开的文件名称为:" + file.getName());
			} else if (result == JFileChooser.CANCEL_OPTION) {
				label.setText("您没有选择任何文件");
			}

			FileInputStream fileInStream = null;

			if (file != null) {
				try {
					// 利用FileInputStream将文件内容放入此数据流中以便读取.
					fileInStream = new FileInputStream(file);
				} catch (FileNotFoundException fe) {
					label.setText("File Not Found");
					return;
				}

				int readbyte;

				try {
					// 以read()方法读取FileInputStream对象内容,当返回值为-1时代表读完此数据流.将所读到的字符显示
					// 在textarea中.
					while ((readbyte = fileInStream.read()) != -1) {
						textarea.append(String.valueOf((char) readbyte));
					}
				} catch (IOException ioe) {
					label.setText("读取文件错误");
				} finally {// 回收FileInputStream对象,避免资源的浪费.
					try {
						if (fileInStream != null)
							fileInStream.close();
					} catch (IOException ioe2) {
					}
				}
			}
		}
		// 实作写入文件的功能.
		if (e.getActionCommand().equals("存储文件")) {
			result = fileChooser.showSaveDialog(f);
			file = null;
			String fileName;
			// 当用户没有选择文件,而是自己键入文件名称时,系统会自动以此文件名建立新文件.
			if (result == JFileChooser.APPROVE_OPTION) {
				file = fileChooser.getSelectedFile();
				label.setText("您选择存储的文件名称为:" + file.getName());
			} else if (result == JFileChooser.CANCEL_OPTION) {
				label.setText("您没有选择任何文件");
			}
			// 写入文件我们使用FileOutputStream,在这个范例中,我们写入文件的方式是将之前内容清除并重新写入.若你想把
			// 新增的内容加在原有的文件内容后面,你可以使用FileOutputStream(String name,Boolean
			// append)这个构造函数.
			FileOutputStream fileOutStream = null;

			if (file != null) {
				try {
					fileOutStream = new FileOutputStream(file);
				} catch (FileNotFoundException fe) {
					label.setText("File Not Found");
					return;
				}

				String content = textarea.getText();

				try {
					fileOutStream.write(content.getBytes());
				} catch (IOException ioe) {
					label.setText("写入文件错误");
				} finally {
					try {
						if (fileOutStream != null)
							fileOutStream.close();
					} catch (IOException ioe2) {
					}
				}
			}
		}
	}
}