Search code examples
javaapplet

Browse button to select directory


I want to create a browse button in my web page to select directory and not file. I know that input type file won't work here but is there any way to do it with Javascript. I want to get the filepath of client machine which is possible in IE but other browser are not supporting but that is fine for me.

The way I got stuck is how to get file directory in button.

Below is the code I am using to call applet from browser but I am getting Detected from bootclasspath: C:\PROGRA~1\Java\jre7\lib\deploy.jar error in browser. I have compiled class file using Java 1.5

<applet code="com.life.draw.BrowsePage.class"></applet>

Code

public class BrowsePage extends JApplet {
@Override
public void paint(Graphics g) {
    // TODO Auto-generated method stub
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("Browse the folder to process");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        System.out.println("getCurrentDirectory(): "+ chooser.getCurrentDirectory());
        System.out.println("getSelectedFile() : "+ chooser.getSelectedFile());
    } else {
        System.out.println("No Selection ");
    }
}
}

Solution

  • Why the hell are you calling this in the your paint method? This is likely trying creating to create new windows EVERY TIME the applet is painted.

    public void paint(Graphics g) {
        // TODO Auto-generated method stub
        JFileChooser chooser = new JFileChooser();
        /*...*/
    

    Instead, create a JButton in your init method and attach an ActionListener to it...

    public void init() {
        setLayout(new GridBagLayout());
        JButton browse = new JButton("...");
        browse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                JFileChooser chooser = new JFileChooser();
                chooser.setCurrentDirectory(new java.io.File("."));
                chooser.setDialogTitle("Browse the folder to process");
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setAcceptAllFileFilterUsed(false);
    
                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    System.out.println("getCurrentDirectory(): "+ chooser.getCurrentDirectory());
                    System.out.println("getSelectedFile() : "+ chooser.getSelectedFile());
                } else {
                    System.out.println("No Selection ");
                }
            }
        });
        add(browse);
    }
    

    You might also like to take a look at What Applets Can and Cannot Do