禁用文件选择器中的新文件夹按钮不能正常工作

时间:2011-04-06 15:29:02

标签: java swing jfilechooser

我使用以下代码禁用新的“文件夹”按钮:

 public void disableNewFolderButton( Container c ) {

     System.out.print("in disable fn");
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"))
    {
        System.out.print("in disable fn");
       b.setEnabled(false);
    }
    }
  else if (comp instanceof Container) {
    disableNewFolderButton((Container)comp);
  }
}
 }

代码在以下行中调用:

   JFileChooser of=new JFileChooser();
    of.setAcceptAllFileFilterUsed(false);
    of.addChoosableFileFilter(new MyFilter());
    disableNewFolderButton(of);

但是,仅在首次显示文件选择器时才会禁用新文件夹按钮。假设我去了一些驱动器,比如说g :,那么按钮再次启用。如何设置正确?

3 个答案:

答案 0 :(得分:6)

这对我有用......

    //Create a file chooser
UIManager.put("FileChooser.readOnly", Boolean.TRUE); 
JFileChooser fc = new JFileChooser();

答案 1 :(得分:4)

禁用“新文件夹”操作(这将禁用该按钮):

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class FileChooserAction
{
    public static void createAndShowUI()
    {
        JFileChooser chooser = new JFileChooser();

        BasicFileChooserUI ui = (BasicFileChooserUI)chooser.getUI();
        Action folder = ui.getNewFolderAction();
        folder.setEnabled(false);

        chooser.showSaveDialog(null);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

答案 2 :(得分:0)

1)它有点愚蠢,但你可以继续在另一个线程中禁用它。直到文件选择器变得不可见 2)隐藏按钮是否有效? b.setVisible(false);

相关问题