I have a JFrame that opens a JFileChooser via an action event.
When this JFrame is disposed and the user opens up a new one and selects the JFileChooser they get one JFileChooser popup for each JFrame that has ever been open(and disposed).
Is this a common issue?
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(null);
fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
System.out.println("Opening: " + file.getAbsolutePath());
filets = file.getAbsolutePath();
String shortName = file.getName();
if(shortName.length() > 9 ){
String roar = shortName.substring(0, 9);
String shortErName = roar+"...";
btnBrowse.setText(shortErName);
}
else {
btnBrowse.setText(shortName);
}
} else {
System.out.println("Error Getting File!");
}
}
});
And my browse button:
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
System.out.println("Opening: " + file.getAbsolutePath());
filets = file.getAbsolutePath();
String shortName = file.getName();
if(shortName.length() > 9 ){
String roar = shortName.substring(0, 9);
String shortErName = roar+"...";
btnBrowse.setText(shortErName);
}
else {
btnBrowse.setText(shortName);
}
} else {
System.out.println("Error Getting File!");
}
}
});
I imagine what’s happening is that
btnBrowseis getting one of theseActionListeners added each time you create aJFrame, but nothing is actually removing those listeners. If it’s the sameJButtonthat survives the dispose of theJFrame— i.e, if the button itself is located elsewhere or if it’s just a member in some other class and you’re reusing it — then this is almost certainly the problem.You could override
dispose()on theJFrameand callbtnBrowse.removeActionListener()to get rid of the listener before callingsuper.dispose().