JButton btnFile = new JButton("Select Excel File");
btnFile.addActionListener(new ActionListener() {
//Handle open button action.
public void actionPerformed(ActionEvent e) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(frmRenamePdfs);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("File: " + file.getName() + ".");
} else {
System.out.println("Open command cancelled by user.");
}
System.out.println(returnVal);
}
});
我似乎无法弄清楚如何从Listener外部访问“file”,即在创建GUI休止符的函数中。我在启动文件选择器的按钮旁边有一个空白文本标签,所以我要做的是存储文件,并将文本标签的文本设置为文件名。
答案 0 :(得分:3)
如何在类级而不是在anon内部类中定义File file
变量?
public class SwingSandbox {
private File file;
public SwingSandbox() {
final JFrame frame = new JFrame("Hello");
JButton btnFile = new JButton("Select Excel File");
btnFile.addActionListener(new ActionListener() {
//Handle open button action.
public void actionPerformed(ActionEvent e) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("File: " + file.getName() + ".");
} else {
System.out.println("Open command cancelled by user.");
}
System.out.println(returnVal);
}
});
frame.getContentPane().add(btnFile);
frame.setSize(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) throws Exception {
new SwingSandbox();
}
}