编辑代码

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) {
                // 在EDT线程中显示文件选择器
                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();
    }
}