如何在jfilechooser中关闭“创建新文件夹”的可见性

时间:2014-08-31 13:51:44

标签: java swing jfilechooser

我的目的是关闭file chooser上的“创建新文件夹”按钮。是否可以设置文件选择器上“创建新文件夹”按钮的可见性?我可以设置以“查看”字开始哪一行的第一个组件的可见性关闭但是我想要设置只有“创建新文件夹”的可见性并不是全部。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

两个建议:

您可以通过访问默认操作并禁用操作来禁用该按钮:

Action folder = fileChooser.getActionMap().get("New Folder");
folder.setEnabled( false );

或者您可以使用反射来访问按钮并使按钮不可见:

//JButton button = SwingUtils.getDescendantOfType(
//  JButton.class, fileChooser, "ToolTipText", "Create New Folder");
//button.setVisible(false);

对于这种方法,您需要使用Swing Utils类。

以下是两种方法的快速演示:

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

public class Main
{
    public static void main(String[] args)
    {
        JFileChooser fileChooser = new JFileChooser();

        Action folder = fileChooser.getActionMap().get("New Folder");
        folder.setEnabled( false );

        // Make the button invisible

        //JButton button = SwingUtils.getDescendantOfType(
        //  JButton.class, fileChooser, "ToolTipText", "Create New Folder");
        //button.setVisible(false);

        fileChooser.showOpenDialog(null);
    }
}

答案 1 :(得分:1)

我使用图标名称来关闭按钮。我的实施是;

JFileChooser fileChooser = new JFileChooser();

// operations related with adjusting JFileChooser user interface

closeButton(fileChooser, "FileChooser.newFolderIcon");
closeButton(fileChooser, "FileChooser.upFolderIcon");

将要调用的主要功能在用户界面上显示按钮

void closeButton(JFileChooser fileChooser, String label){
    Icon icon = UIManager.getIcon(label);
    closeButtonHelper(fileChooser.getComponents(), icon);
}

void closeButtonHelper(Component[] containers, Icon icon) {
    for(Object iterator:containers){

        if(iterator instanceof JButton){

            Icon temp = icon.getIcon();

            if(temp != null && temp == icon){
                 (JButton.class.cast(iterator)).setVisible(false);
            }

        } else 
        if(iterator instanceof Container){
            doVisibleHelper(Container.class.cast(iterator).getComponents(), icon);
        }
    }
}

对于切换按钮,只需添加新的if-then-else语句,例如;

if(iterator instanceof JToggleButton){

    Icon temp = icon.getIcon();

    if(temp != null && temp == icon){
         (JToggleButton.class.cast(iterator)).setVisible(false);
    }

} else