我恭敬地不同意。它有一个工具,我一直成功地使用它,特别是与 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);
}
}
警告:这会在移除的组件曾经驻留的地方留下一点空隙。我无法确定其来源;如果有人有线索,请发布。
结果是这样的(注意我做了代码片段中没有显示的其他修改);
![在此处输入图像描述](https://i.stack.imgur.com/Iz0ht.png)