我有一个通过动作事件打开JFileChooser的JFrame。
当这个JFrame被释放并且用户打开一个新的JFrame并选择JFileChooser时,他们会为每个打开(并处置)的JFrame获得一个JFileChooser弹出窗口。
这是一个常见问题吗?
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!");
}
}
});
我的浏览按钮:
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!");
}
}
});
答案 0 :(得分:3)
我认为正在发生的事情是btnBrowse
每次创建ActionListener
时都会添加其中一个JFrame
,但实际上并没有删除这些侦听器。如果处理JButton
后仍然存在相同的JFrame
- 即,如果按钮本身位于其他地方,或者如果它只是其他类中的成员并且您正在重复使用它 - 那么这几乎肯定是问题所在。
您可以覆盖dispose()
上的JFrame
,并在致电btnBrowse.removeActionListener()
之前致电super.dispose()
以取消听众。
答案 1 :(得分:0)
编辑:一些解释我的意思的代码
JFrame myFrame = new JFrame();
JButton someButton = new JButton();
void addActionListenerToButton() {
someButton.addActionListener(new ActionListener() {
new JFileChooser().showOpenDialog(null);
});
}
void handler() {
myFrame.add(someButton);
addActionListerToButton();
myFrame.show();
someButton.click(); // that method does not exist, it is meant as the user clicks.
myFrame.dispose();
}
void main() {
handler(); // thats the first run where one JFileChooser is seen
handler(); // thats the second one, now you have two JFileChoosers.
}