1

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);
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Loligans
  • 497
  • 9
  • 24

2 Answers2

2

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.

William Morrison
  • 10,953
  • 2
  • 31
  • 48
  • [hmmm disagree](http://stackoverflow.com/questions/6309407/remove-top-level-container-on-runtime) – mKorbel Jul 03 '13 at 19:10
  • The amount of time it takes to create a file chooser class is so gnomic ant enough to consider using a lazy loading approach,,but keeping the created instance if you think it's going to be reused. If even set up a global one in the past and configured it as needed – MadProgrammer Jul 03 '13 at 20:50
0

The Garbage collector should take care of deleting your JFlieChooser object. You can read more about how the Garbage collector works here

Marco Corona
  • 812
  • 6
  • 12