java JFileChooser 如何暂时禁用文件选择window

java JFileChooser how to temporarily disable file selection window

有没有办法暂时禁用 JFileChooser window 中的文件选择器? 我创建了自定义预览 JPanel,我只需要在文件预览为 done/created 之后选择下一个文件(当在文件选择器中选择此类 obj 文件时,它会从 Wavefront OBJ 文件创建图像 window). 也许某种禁用整个文件选择 window 部分?

编辑:

我在这里搜索了一下,首先找到了 post Start a JFileChooser with files ordered by date. Now if I understood it right, then according to it, this piece of code should in fact enabling access to FilePane inside the JFileCHooser (of course, I downloaded the SwingUtils.java class):

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 window 的文件选择部分,但不幸的是它什么也没做。

所以过了一会儿我自己解决了这个问题,通过进一步使用上面的代码结束了下面这个功能块:

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);