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 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