Disable the JFileChooser's "New folder" buttonTag(s): Swing


No easy way to disable the "New Folder" button. You need to iterate the JFileChooser components until the right one and disable it.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;


public class DemoJFileChooser extends JPanel
   implements ActionListener {
   JButton go;

   JFileChooser chooser;
   String choosertitle;

  public DemoJFileChooser() {
    go = new JButton("Do it");
    go.addActionListener(this);
    add(go);
   }

  public void actionPerformed(ActionEvent e) {
    int result;

    chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle(choosertitle);

    disableNewFolderButton(chooser);

    //
    int rc = chooser.showOpenDialog(this);
    if (rc == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): "
         +  chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : "
         +  chooser.getSelectedFile());
    }
    else {
      System.out.println("No Selection!");
    }
  }


  public void disableNewFolderButton( Container c ) {
    int len = c.getComponentCount();
    for (int i = 0; i < len; i++) {
      Component comp = c.getComponent(i);
      if (comp instanceof JButton) {
        JButton b = (JButton)comp;
        Icon icon = b.getIcon();
        if (icon != null
             && icon == UIManager.getIcon("FileChooser.newFolderIcon"))
           b.setEnabled(false);
        }
      else if (comp instanceof Container) {
        disableNewFolderButton((Container)comp);
      }
    }
  }

  public Dimension getPreferredSize(){
    return new Dimension(200, 200);
  }

  public static void main(String s[]) {
    JFrame frame = new JFrame("");
    DemoJFileChooser panel = new DemoJFileChooser();
    frame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
        }
      }
    );
    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
  }
} 

blog comments powered by Disqus