This example show you how to change the color of the selected node of the JTree
component. It shows you how to set the node background color, the font color and the selected node border color.
To do this you need to obtain the DefaultTreeCellRenderer
object from the JTree
instance and modified the selection color of the node.
package org.kodejava.swing;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
public class JTreeTextSelectionColorDemo extends JFrame {
public JTreeTextSelectionColorDemo() throws HeadlessException {
initializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new JTreeTextSelectionColorDemo().setVisible(true));
}
private void initializeUI() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Department");
DefaultMutableTreeNode book = new DefaultMutableTreeNode("Books");
DefaultMutableTreeNode fiction = new DefaultMutableTreeNode("Fictions");
DefaultMutableTreeNode science = new DefaultMutableTreeNode("Sciences");
DefaultMutableTreeNode text = new DefaultMutableTreeNode("Text Books");
DefaultMutableTreeNode children = new DefaultMutableTreeNode("Children");
root.add(book);
book.add(fiction);
book.add(science);
book.add(text);
book.add(children);
JTree tree = new JTree(root);
// Get the DefaultTreeCellRenderer instance of the JTree
// component. Then we customize the color of the selection
// node using blue background, white font color and black
// border.
DefaultTreeCellRenderer renderer =
(DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setTextSelectionColor(Color.white);
renderer.setBackgroundSelectionColor(Color.blue);
renderer.setBorderSelectionColor(Color.red);
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(250, 350));
getContentPane().add(pane);
}
}
Latest posts by Wayan (see all)
- How do I use the LongToDoubleFunction functional interface in Java? - March 15, 2025
- How do I use the LongSupplier functional interface in Java? - March 14, 2025
- How do I use the LongPredicate functional interface in Java? - March 14, 2025