由于某种原因,无论何时我尝试选择一个文本文件,即使目录中显然有一个文本文件,它也不会显示在文件选择器中。我的代码有问题吗?
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);
,它应该可以工作。