I have a JButton which launches a JFileChooser. However the JFileChooser often takes a few seconds to come up, during which time the user might think that nothing is happening. I tried to make the button become disabled until the JFileChooser is finished with, but the disabling of the button doesn’t even happen until the JFileChooser is loaded. Is there something I can do?
My code:
public void actionPerformed(ActionEvent e) {
System.err.println("clicked");
((JButton) e.getSource()).setEnabled(false);
System.err.println("set");
JFileChooser b = new JFileChooser("C:\\");
b.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int res = b.showOpenDialog((Component) e.getSource());
if (res == JFileChooser.APPROVE_OPTION) {
try {
//Blah
}
catch (Exception err) {
JDialog j = new JDialog(window, "An error occured:\n" + err.getMessage());
}
}
((JButton) e.getSource()).setEnabled(true);
}
Move these lines..
..from the action performed method to the constructor of the action listener, change them to..
..then declare..
..as a class attribute (so it is visible to the action performed method).
You might also want to give it a better name.
The chooser will be constructed when the class is created, and be ready for use when needed. This has the added benefit that the chooser will remember the position, size, path & file display type, the subsequent times the user activates the button.
Yet another strategy is to declare the chooser as a class attribute, don’t instantiate it in the constructor, but check in the action performed if it is
null, and if so, create and configure it.Continued..
With the last strategy I outlined, I was considering adding something that I will add now.
..Continued
..Of course, that last method will give exactly the same problem you describe, but just once when the user 1st clicks the button. For that situation, you should probably be looking to pop a
JOptionPanewith an indeterminateJProgressBarfrom inside aSwingWorker.Obviously, a
SwingWorkercreates a newThread, but OTOH,Threadobjects in Java are cheap. There are a number of them running for any app. with a GUI. A couple more will not hurt.