Set selected row for JTree in Java

Description

The following code shows how to set selected row for JTree.

Example


import java.awt.BorderLayout;
/*from   ww w .j  a  v  a2s.co  m*/
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode mercury = new DefaultMutableTreeNode("Mercury");
    root.add(mercury);
    DefaultMutableTreeNode venus = new DefaultMutableTreeNode("b");
    root.add(venus);
    DefaultMutableTreeNode mars = new DefaultMutableTreeNode("java2s.com");
    root.add(mars);
    JTree tree = new JTree(root);

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);


    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    tree.setSelectionRow(2);
    TreePath path = tree.getSelectionPath();
    MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();

    MutableTreeNode newNode = new DefaultMutableTreeNode("green");

    model.insertNodeInto(newNode, node, node.getChildCount());
  }
}

The code above generates the following result.

Set selected row for JTree in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer