有没有办法暂时禁用JFileChooser窗口中的文件 Select 器?

EDIT:

我在这里搜索了一下,找到了Start a JFileChooser with files ordered by date号帖子.如果我理解正确,那么根据它,这段代码实际上应该能够访问JFileCHooser中的FilePane(当然,我首先下载了SwingUtils.java类):

JTable table = SwingUtils.getDescendantsOfType(JTable.class, fileChooser).get(0);

但当我这么做的时候,我在NetBeansIDE中得到了一个错误:java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

我还找到了post How to disable file input field in JFileChooser?,根据它,这段代码访问JFileChooser的文本字段,显示所选的文件名:

import java.awt.Frame;
import java.lang.reflect.Field;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.plaf.metal.MetalFileChooserUI;

public class FileChooser {

public static void main(String[] args) throws Exception{
  Frame f = new JFrame();
  JFileChooser jFileChooser = new JFileChooser();
  MetalFileChooserUI ui = (MetalFileChooserUI)jFileChooser.getUI();
  Field field = MetalFileChooserUI.class.getDeclaredField("fileNameTextField");
  field.setAccessible(true);
  JTextField tf = (JTextField) field.get(ui);
  tf.setEditable(false);
  tf.setEnabled(false);
  jFileChooser.showDialog(f, "Select");
  f.dispose();
 }
}

所以,通过判断所有可用字段,我发现有一个名为"filePane".所以我冒了一个风险,试着模仿上面的代码,只是做了一些修改,这样FilePane个目标就会变成这样:

Field fieldB = MetalFileChooserUI.class.getDeclaredField("filePane");
fieldB.setAccessible(true);
FilePane filePane = (FilePane) fieldB.get(ui);
filePane.setEnabled(false);

我原以为上面的代码会禁用JFileChooser窗口的文件 Select 部分,但不幸的是,它什么也没做.

推荐答案

因此,过了一段时间,我自己解决了这个问题,通过进一步使用上面的代码,最终得到下面这个功能块:

FilePane filePane = SwingUtils.getDescendantsOfType(FilePane.class, fileChooser).get(0);
filePane.setEnabled(false);//<- this line doesn't work, but I'll leave it here so others know
filePane.setVisible(false);

Java相关问答推荐

将具有多个未知字段的SON映射到Java POJO

RxJava PublishSubject缓冲区元素超时

了解Android Studio中的调试器输出

所有 case 一起输入时输出错误,而单独放置时输出正确

Mapstruct不能正确/完全映射属性

如何在Java记录中设置BigDecimal类型属性的精度?

如何在Application.yaml中连接字符串?

如何在antlr4中跳过所有反斜杠-换行符而保留换行符?

如何在JavaFX中处理多个按钮

为什么我的回收视图会显示重复的列表?

Kotlin Val是否提供了与Java最终版相同的可见性保证?

Spring Boot&;Docker:无法执行目标org.springframework.boot:spring-boot-maven-plugin:3.2.0:build-image

try 使用预准备语句占位符获取信息时出现Try-With-Resources错误

在应用getCellFormula()时,Excel引用中的文件名始终为";[1]";使用Apache POI()

泛型与泛型问题的完美解决方案?

在Java中比较同一多维数组的两个不同的字符串元素

让标签占用JavaFX中HBox的所有可用空间

Java编译器是否进行了持续的折叠优化,以及如何进行判断?

获取401未经授权,即使在标头中设置了浏览器名称和cookie

为什么 Random() 的行为不符合预期?