首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何将JFileChooser限制为目录?

要将JFileChooser限制为目录,您可以使用setFileSelectionMode方法。以下是一个简单的Java示例,演示如何创建一个JFileChooser,将其限制为目录选择,并获取所选目录的路径。

代码语言:java
复制
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DirectoryChooser {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Directory Chooser");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        JButton selectDirectoryButton = new JButton("Select Directory");
        selectDirectoryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int result = fileChooser.showOpenDialog(frame);
                if (result == JFileChooser.APPROVE_OPTION) {
                    String directoryPath = fileChooser.getSelectedFile().getPath();
                    JOptionPane.showMessageDialog(frame, "Selected Directory: " + directoryPath);
                }
            }
        });

        frame.getContentPane().add(selectDirectoryButton, BorderLayout.CENTER);
        frame.setVisible(true);
    }
}

这个示例将创建一个简单的窗口,其中包含一个按钮。当单击该按钮时,将显示一个JFileChooser,限制为仅选择目录。选择目录后,将显示一个消息框,显示所选目录的路径。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券