How to disable File Name Input in JFileChooser in Java

JFileChooser is a very powerful Component in Java. It even enables filtering of file names. However, there is no direct method to prevent a user from entering the File Name input in it.

The following method disables the JTextField File input text box in  JFileChooser, by basically taking the JFileChooser as a Component, looking for a Component that matches JTextField and disabling the JTextField input.

public boolean disableTextField(Container container) {
   Component[] comps = container.getComponents();

   for (Component comp : comps) {
      if (cmp instanceof JTextField) {
         ((JTextField) comp).setEnabled(false);
         return true;
      }
      if (comp instanceof Container) {
         if (disableTextField((Container) comp)) return true;
      }
   }
   return false;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s