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.example.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();
}
private void initializeUI() {
setSize(150, 300);
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.black);
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(150, 300));
getContentPane().add(pane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JTreeTextSelectionColorDemo().setVisible(true);
}
});
}
}
Latest posts by Wayan (see all)
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020