The program below demonstrate how to change the default icons of a JTree
component. We can change tree icons of the component which are the closed icon, the open icon and the leaf icon.
package org.kodejava.swing;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.util.Objects;
public class JTreeChangeIcon extends JFrame {
public JTreeChangeIcon() throws HeadlessException {
intializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new JTreeChangeIcon().setVisible(true));
}
private void intializeUI() {
setSize(500, 500);
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);
// Change the default JTree icons
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
Icon closedIcon = new ImageIcon(Objects.requireNonNull(
this.getClass().getResource("/images/lightbulb_off.png")));
Icon openIcon = new ImageIcon(Objects.requireNonNull(
this.getClass().getResource("/images/lightbulb.png")));
Icon leafIcon = new ImageIcon(Objects.requireNonNull(
this.getClass().getResource("/images/lightning.png")));
renderer.setClosedIcon(closedIcon);
renderer.setOpenIcon(openIcon);
renderer.setLeafIcon(leafIcon);
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(500, 500));
getContentPane().add(tree);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024