如何在jfilechooser中关闭“创建新文件夹”的可见性
问题描述:
我的目标是关闭file chooser上的“创建新文件夹”按钮。是否可以在文件选择器上设置“创建新文件夹”按钮的可见性?我可以设置第一个组件的可见性,哪个行以“look in”单词开始,但我只想设置“创建新文件夹”的可见性不是全部。我怎样才能做到这一点 ?如何在jfilechooser中关闭“创建新文件夹”的可见性
答
两个建议:
您可以通过访问默认操作和禁用不可动作按钮:
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);
}
}
答
我已经使用图标名称关闭按钮。我的实施是;
JFileChooser fileChooser = new JFileChooser();
// operations related with adjusting JFileChooser user interface
closeButton(fileChooser, "FileChooser.newFolderIcon");
closeButton(fileChooser, "FileChooser.upFolderIcon");
这是会被要求
主要功能DIS-出现用户界面
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