Andreas Neophytou
Andreas Neophytou

Reputation: 151

Java/Swing: Why is my JFileChooser opening twice?

So I have created a Java GUI application, I have a main form, and I run this class PathBrowser by clicking a jbutton, The JFileChooser runs twice though, I have tried adding the opendialog from my mainform so I can have the same logo on the window.

Here's my code:

public class PathBrowser {
public static String filepath = null;
public static void main(String[] args)
{

    JButton select = new JButton();
    JFileChooser browse = new JFileChooser();
    //add the icon of main form for JFileChooser
    //OPENS TWICE?! Error
    browse.showOpenDialog(MainForm.frame);

    //if blank goes to user/documents. Unsure about other OSes
    browse.setCurrentDirectory(new java.io.File("C:/"));
    browse.setDialogTitle("Browse Folder");
    browse.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //when clicked open (approve option)
    if (browse.showOpenDialog(select) == JFileChooser.APPROVE_OPTION){
        //folder has peen selected
        MainForm.selfolder = true;
        //add the path to the string filepath
        filepath = (browse.getSelectedFile().getAbsolutePath());
        System.out.println("The path for the server is: "+browse.getSelectedFile().getAbsolutePath());
        //add the information to the textarea
        MainForm.textArea.setText("The path for the server is: "+browse.getSelectedFile().getAbsolutePath());
    }

}

}

Thanks

Upvotes: 1

Views: 1320

Answers (1)

Arnaud
Arnaud

Reputation: 17524

You are calling browse.showOpenDialog twice, that's why you get it twice.

Just remove this line :

browse.showOpenDialog(MainForm.frame);

And to keep the frame's icon, replace

browse.showOpenDialog(select)

with

browse.showOpenDialog(MainForm.frame)

Upvotes: 6

Related Questions