Search code examples
javaswingdisposejfilechooser

How to dispose of the JFileChooser


Every time the button is pressed, does it create a new JFileChooser object? Is it possible to dispose it, or does java do that automatically for me?

public void buttonPressed(){
    JFileChooser chooser = null;
    LookAndFeel previousLF = UIManager.getLookAndFeel();
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        chooser = new JFileChooser();
        UIManager.setLookAndFeel(previousLF);
    } catch (IllegalAccessException | UnsupportedLookAndFeelException | InstantiationException | ClassNotFoundException e) {}

    File location = new File("C:\\");
    chooser.setCurrentDirectory(location);
    chooser.setDialogTitle("Select Your Directory");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.showOpenDialog(frame);
}

Solution

  • Java automatically disposes of unused memory using a Garbage collector, so yes. It will dispose of your JFileChooser object automatically.

    Also yes, each time your button is pressed, if you call buttonPressed, a new JFileChooser will be created. This is acceptable.