Skip to content
Advertisement

java JFileChooser how to temporarily disable file selection window

Is there a way how to temporarily disable file chooser in the JFileChooser window? I created custom preview JPanel and I need the next file selection to be made only after the file preview is done/created (it created image from Wavefront OBJ files when such obj file is selected in the file chooser window). Maybe some sort of disabling the whole file selection window part?

EDIT:

I was searching around here a bit more and found 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 first):

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

But when I do that, I got error in NetBeansIDE saying: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 Does anyone know why?

I also found post How to disable file input field in JFileChooser?, according to which this piece of code accessing the JFileChooser’s textfield showing the selected file name:

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

So, by inspecting all available fields I found out there is one called “filePane”. So I took a risk and try to imitate the above code just with a few changes so that the FilePane would be targeted instead like this:

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

I thought the code above would disable the file selection part of the JFileChooser window, but it did absolutely nothing, unfortunately.

Advertisement

Answer

So after a while I’ve solved it myself by playing further with the above code ending up with this functioning piece below:

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);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement