java - JFileChooser 不显示文本文件

标签 java swing jfilechooser filechooser

由于某种原因,每当我尝试选择一个文本文件时,即使目录中明显有一个文本文件,它也不会显示在文件选择器中。我的代码有问题吗?

package me.riley.logreader;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

public class LogReader {

    public static void main(String[] args) {
        ActionListeners actions = new ActionListeners();
        JFrame frame = new JFrame("Log Reader");

        //Window options 
        frame.setVisible(true);
        frame.setSize(500,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Adds the panel to the frame
        JPanel panel = new JPanel();
        frame.add(panel);

        //Creates the button and places it inside the panel
        JButton button = new JButton("Click Here");
        button.setLocation(10, 10);
        panel.add(button);
        button.addActionListener(actions);

        //Allows user to open a text file
        JFileChooser filechooser = new JFileChooser();
        filechooser.setFileFilter(new FileNameExtensionFilter(".txt", "txt"));
        filechooser.setDialogTitle("Choose a text file");
        filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        filechooser.showOpenDialog(null);

        }

    }

最佳答案

这是因为您已将 FileSelectionMode 设置为 DIRECTORIES_ONLY。

删除filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);它应该可以工作。

关于java - JFileChooser 不显示文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59622150/

相关文章:

java - 是什么导致我的 java awt 和 swing 浏览器的后退按钮无法正常工作?

java - 在 JFileChooser 中用鼠标拖动选择多个文件

java - 是否可以在运行时访问类型参数上的注释?

java - 使用 Java 应用程序连接应用程序服务器并检索数据的最佳方式

Java 桌面通知 Ubuntu

java - java swing对象之间的细微差别

java - 从另一个类调用类

java - 在Java中设置文件创建时间戳

java - TrueZip - 如何获取 Zip 存档中文件夹的大小

java - 从 Java 应用程序安装程序中查找 Mac OS X 上所有可用的 JRE