Simple example of JFileChooser

Download code from Small.zip


Test1.java

// Test1.java
import java.awt.Graphics;
import java.awt.FontMetrics;
import java.awt.geom.Rectangle2D;
import java.io.*;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JFileChooser;

public class Test1 extends JPanel
{
    public void paintComponent(Graphics g)
    {
	super.paintComponent( g );
	int width = getWidth();
	int height = getHeight();
	String str = String.format("width %d height %d",width,height);
	FontMetrics fm = g.getFontMetrics();
	Rectangle2D rect = fm.getStringBounds(str,g);
	width -= rect.getWidth();
	height -= rect.getHeight();
	g.drawString(str,width/2,height/2);
    }

    public static void main( String args[] )
    {
	Test1 panel = new Test1();
	JFrame application = new JFrame("Test1");
	application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	application.add(panel);
	application.setSize(200,200);
	application.setVisible(true);

	//
	
	//Create a file chooser
/* Method 1
        JFileChooser fc = new JFileChooser();
	File cur = fc.getCurrentDirectory();
	System.out.println("Current directory: " + cur.getName());
	fc.setCurrentDirectory(new File("."));
*/
// Method 2
	JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));


	int returnVal = fc.showOpenDialog(application);
	System.out.println("Returned: " + returnVal);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
		System.out.println("Filename: " + file.getName());
	}
    }
}


Maintained by John Loomis, updated Tue Feb 24 21:27:01 2015