2

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

 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: ,然后按钮再次启用。如何设置正确?

4

3 回答 3

7

这对我有用...

    //Create a file chooser
UIManager.put("FileChooser.readOnly", Boolean.TRUE); 
JFileChooser fc = new JFileChooser();
于 2011-04-06T16:09:47.550 回答
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();
            }
        });
    }
}
于 2011-04-06T16:16:17.523 回答
0

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

于 2011-04-06T15:40:45.917 回答