Java如何删除JTree默认图标?
您可以JTree通过修改树单元格渲染器对象来删除默认图标。要获取单元格渲染器,请调用JTree.getCellRenderer(),它将返回一个DefaultTreeCellRenderer对象。然后,你可以通过设置删除图标null价值的setLeafIcon(),setClosedIcon()和setOpenIcon()。
package org.nhooo.example.swing; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import java.awt.*; public class JTreeRemoveIcon extends JFrame { public JTreeRemoveIcon() throws HeadlessException { initializeUI(); } private void initializeUI() { setSize(200, 400); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Address Book"); DefaultMutableTreeNode a = new DefaultMutableTreeNode("A"); DefaultMutableTreeNode b = new DefaultMutableTreeNode("B"); DefaultMutableTreeNode c = new DefaultMutableTreeNode("C"); DefaultMutableTreeNode aContact = new DefaultMutableTreeNode("Alice"); DefaultMutableTreeNode bContact = new DefaultMutableTreeNode("Bob"); DefaultMutableTreeNode cContact = new DefaultMutableTreeNode("Carol"); root.add(a); root.add(b); root.add(c); a.add(aContact); b.add(bContact); c.add(cContact); JTree tree = new JTree(root); //删除默认的JTree图标 DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); renderer.setLeafIcon(null); renderer.setClosedIcon(null); renderer.setOpenIcon(null); JScrollPane pane = new JScrollPane(tree); pane.setPreferredSize(new Dimension(200, 400)); getContentPane().add(tree); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new JTreeRemoveIcon().setVisible(true); } }); } }