JFileChoser

文件选择的一个小例子:

package v2.chapter06.TableCellRenderTest.my;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.filechooser.FileFilter;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				JFrame frame = new TestFrame();
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
			}
		});

	}

}

class TestFrame extends JFrame {
	public TestFrame() {
		setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		setTitle("testFrame");
		JMenu file = new JMenu("file");
		JMenuItem openItem = new JMenuItem("open");
		JMenuItem exitItem = new JMenuItem("exit");
		exitItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		openItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				openFile();
			}
		});
		file.add(openItem);
		file.add(exitItem);
		JMenuBar bar = new JMenuBar();
		bar.add(file);

		setJMenuBar(bar);

	}

	public void openFile() {
		
		fileChoose = new JFileChooser(new File("./"));
		
		
		fileChoose.setFileFilter(new FileFilter() {

			@Override
			public String getDescription() {

				return "XML file";
			}

			public boolean accept(File f) {

				return f.isDirectory()
						|| f.getName().toLowerCase().endsWith(".xml");
			}
		});

		int r = fileChoose.showOpenDialog(this);
		if (r != JFileChooser.APPROVE_OPTION)
			return;
		final File file = fileChoose.getSelectedFile();
		System.out.println(file.getName());
	}

	private JFileChooser fileChoose;
	private static final int DEFAULT_WIDTH = 600;
	private static final int DEFAULT_HEIGHT = 400;
}

 

你可能感兴趣的:(java,xml,swing,F#)