views:

595

answers:

5

I am trying to create my first UI page though Swing. In this page I wish to browse for a file. Can someone please help me achieve this?

+2  A: 

You seem to want a JFileChooser.

Joachim Sauer
A: 

Add an actionListener on the button to open a JFileChooser

Trigger
Hi thanks Trigger, but would adding an action on the buttion help me to set the same value in the text box that would be bisides the button as wel?
NewToJava
+7  A: 

Check this tutorial page from Sun: http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html.

Basic implementation involves:

//Create a file chooser
final JFileChooser fc = new JFileChooser();
...
//In response to a button click:
int returnVal = fc.showOpenDialog(aComponent);

The return value gives you info about whether the user clicked "ok" or "cancel" etc. and you can then query the File Chooser object to find out what file was selected.

xan
A: 

Thanks everybody... so is it that I would need to create a text box and a button manually and then add action for the button to call JFileChooser?

NewToJava
yes, exactly ... there is a lot of things to do by hand when coding Swing UI.
Guillaume
+1  A: 

On this page you will find CodeExample how the JFileChooser works.

// This action creates and shows a modal open-file dialog.
    public class OpenFileAction extends AbstractAction {
        JFrame frame;
        JFileChooser chooser;

    OpenFileAction(JFrame frame, JFileChooser chooser) {
        super("Open...");
        this.chooser = chooser;
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent evt) {
        // Show dialog; this method does not return until dialog is closed
        chooser.showOpenDialog(frame);

        // Get the selected file
        File file = chooser.getSelectedFile();
    }
};

// This action creates and shows a modal save-file dialog.
public class SaveFileAction extends AbstractAction {
    JFileChooser chooser;
    JFrame frame;

    SaveFileAction(JFrame frame, JFileChooser chooser) {
        super("Save As...");
        this.chooser = chooser;
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent evt) {
        // Show dialog; this method does not return until dialog is closed
        chooser.showSaveDialog(frame);

        // Get the selected file
        File file = chooser.getSelectedFile();
    }
};
Markus Lausberg