import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyWindow extends JFrame {
public MyWindow() {
super("打开文件");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("打开文件");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("选择文件");
int result = chooser.showOpenDialog(MyWindow.this);
if (result == JFileChooser.APPROVE_OPTION) {
String file = chooser.getSelectedFile().getPath();
System.out.println("用户选择的文件路径:" + file);
}
}
});
}
});
getContentPane().add(button);
setVisible(true);
}
public static void main(String[] args) {
new MyWindow();
}
}