如何从 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);
}
我谨表示不同意。那里is我一直成功地使用它,特别是与 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);
}
}
Caveat:这会在移除的组件曾经所在的位置留下一点间隙。我无法确定其来源;如果有人有线索,请发帖。
Result is like this (note that I make other modifications not shown in code snippet);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)