Swing文件选择器:JFileChooser的使用

2025-10-16 11:59:43

1、构造方法1:

JFileChooser():创建一个指向用户默认目录的 JFileChooser。

构造方法2:

JFileChooser(File currentDirectory):使用指定 File 作为路径来创建 JFileChooser。

构造方法3:

JFileChooser(String currentDirectoryPath):创建一个使用指定路径的 JFileChooser。

Swing文件选择器:JFileChooser的使用

Swing文件选择器:JFileChooser的使用

Swing文件选择器:JFileChooser的使用

1、int showOpenDialog(Component parent):弹出打开文件对话框。

int showSaveDialog(Component parent):弹出保存文件对话框。

1、创建一个窗体,窗体中有一个浏览按钮,点击这个按钮会弹出文件选择器,选择文件后会在文本框和窗体中显示选中文件的路径,如果没有选择文件则提示“未”选中文件

2、声明要用到的变量,然后实例化它们,并添加这些组件到JFrame窗体

Swing文件选择器:JFileChooser的使用

3、实现浏览按钮的监听

Swing文件选择器:JFileChooser的使用

4、效果如下:

Swing文件选择器:JFileChooser的使用

Swing文件选择器:JFileChooser的使用

Swing文件选择器:JFileChooser的使用

Swing文件选择器:JFileChooser的使用

5、Demo28_JFileChooser 类代码如下:

public class Demo28_JFileChooser {

private JLabel label=new JLabel("所选文件路径:");

private JLabel label2 = new JLabel("",JLabel.CENTER);

    private JTextField jtf=new JTextField(25);

    private JButton button=new JButton("浏览");

public static void main(String[] args){

        new Demo28_JFileChooser();

    }

    public Demo28_JFileChooser() {

    JFrame jf=new JFrame("文件选择器");

        JPanel panel=new JPanel();

        panel.add(label);

        panel.add(jtf);

        panel.add(button);

        label2.setFont(new Font("宋体", 1, 25));

        jf.add(panel,BorderLayout.NORTH);

        jf.add(label2);

        SwingUtils.setCenter(jf);//设置窗体大小600*800并居中

        jf.setVisible(true);

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        button.addActionListener(new MyActionListener());  

    }

  //Action事件处理

    class MyActionListener implements ActionListener{

        @Override

        public void actionPerformed(ActionEvent arg0){

            JFileChooser fc=new JFileChooser("D:\\");

            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);  //可以选择文件和文件夹

            int val=fc.showOpenDialog(null);    //文件打开对话框

//          int val=fc.showSaveDialog(null); //弹出保存文件对话框。

            if(val==fc.APPROVE_OPTION){

                //正常选择文件

                jtf.setText(fc.getSelectedFile().toString());

                label2.setText("选择了文件:【"+fc.getSelectedFile().getAbsolutePath()+"】");

            }else{

                //未正常选择文件,如选择取消按钮

                jtf.setText("未选择文件");

            }

        }

    }

}

6、SwingUtils 类代码如下:

public class SwingUtils {

public static void setCenter(JFrame jf) {

int screenWidth=Toolkit.getDefaultToolkit().getScreenSize().width;

int screenHeight=Toolkit.getDefaultToolkit().getScreenSize().height; 

int jframeWidth = 800;

int jframeHeight = 600;

jf.setBounds((screenWidth/2)-(jframeWidth/2), (screenHeight/2)-(jframeHeight/2), 

        jframeWidth, jframeHeight);

}

}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢