4

如何从 JFileChooser 中删除组件(文件类型);标签及其组合框?

我有以下代码:

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setDialogTitle("Select Folder");
fileChooser.setApproveButtonText("Select Folder");
fileChooser.setAcceptAllFileFilterUsed(false);

hideComponents(fileChooser.getComponents());

private void hideComponents(Component[] components) {

for (int i= 0; i < components.length; i++) {
  if (components[i] instanceof JPanel)
    hideComponents(((JPanel)components[i]).getComponents());
  else if (//component to remove)//what do I check for in here?
    components[i].setVisible(false);
}
4

2 回答 2

4

我恭敬地不同意。有一个工具,我一直成功地使用它,特别是与 JFileChooser 一起使用,特别是让被诅咒的野兽在 DOS 和 Mac 上都工作。网上有很多例子;这是另一个,从我的工作小程序中挑选出来的。(此代码段还设置所有组件的背景颜色)。

简而言之:原始海报走在正确的轨道上 - 迭代 JFileChooser.getComponents()。它们不容易识别一个组件,所以我要做的是寻找一个文本标签,然后得到它想要的祖先。然后,您可以使用 Container.getLayout().remove(component) 从布局中删除它,或者,您可以 setVisible(false),或者有时可以通过 setPreferredSize(new Dimension(0,0)) 使其消失。

// in wrapper:
modifyJChooser(fileChooser.getComponents(), Color.white);

// in component:
private void modifyJChooser(Component[] jc, Color bg) {

    for (int i = 0; i < jc.length; i++) {
        Component c = jc[i];

        // hide file name selection
        if (c.getClass().getSimpleName().equals("MetalFileChooserUI$3")) {
            c.getParent().setVisible(false);
        }

        if (c instanceof JComboBox) {
            Object sel = ((JComboBox) c).getSelectedItem();
            if (sel.toString().contains("AcceptAllFileFilter")) {
                c.setVisible(false);
            }
        } else if (c instanceof JLabel) {
  // **** This is the part that the original poster is looking for ****
            String text = ((JLabel) c).getText();
            if (text.equals("Files of Type:") || text.equals("File Name:") || text.equals("Folder Name:")) {
                c.getParent().getParent().remove(c.getParent());
            }
        } else if (c instanceof JButton) {
            JButton j = (JButton) c;
            String txt = j.getText();
            if (txt != null) {
                if (JCHOOSER_NEW_FOLDER.equalsIgnoreCase(txt)) {
                    j.getParent().setVisible(false); // Disable New Folder on Mac OS
                } else if (JCHOOSER_BTN_CANCEL.equalsIgnoreCase(txt)) {
                    Component parent = c.getParent();
                    ((Container) parent).remove(c);
                }
            }
        }

        if (c instanceof Container)
            modifyJChooser(((Container) c).getComponents(), bg);

        c.setBackground(bg);
    }

}

警告:这会在移除的组件曾经驻留的地方留下一点空隙。我无法确定其来源;如果有人有线索,请发布。

结果是这样的(注意我做了代码片段中没有显示的其他修改); 在此处输入图像描述

于 2012-03-26T22:48:26.783 回答
0

JFileChooser 并非设计为隐藏其组件。API 中没有执行此操作的工具。因为这些组件是私有的,所以您无权访问它们,也无法编写代码来自己隐藏它们。

你可能不应该这样做。您可以通过设置“所有文件”过滤器而不是其他过滤器来禁用控件,在这种情况下,组件变得无关紧要。

从技术上讲,您可以通过使用反射并违反类保护来做到这一点,但除非它对您的应用程序绝对至关重要,否则不要这样做。

于 2011-11-29T17:54:47.747 回答