Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jtree programmatic multi selection

Is there an ability to select multiple tree nodes in JTree programmatically? I've set multiselection mode by tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);

And all I need - make my application be able to select some nodes programmatically. But I've didn't found the way how to do that. Could anybody give advice how to solve this?

Thanks

like image 395
stemm Avatar asked Dec 17 '22 11:12

stemm


2 Answers

import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class TreeWithMultiDiscontiguousSelections {

    public static void main(String[] argv) {
        JTree tree = new JTree();
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
        int treeSelectedRows[] = {3, 1};
        tree.setSelectionRows(treeSelectedRows);
        TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
                JTree treeSource = (JTree) treeSelectionEvent.getSource();
                System.out.println("Min: " + treeSource.getMinSelectionRow());
                System.out.println("Max: " + treeSource.getMaxSelectionRow());
                System.out.println("Lead: " + treeSource.getLeadSelectionRow());
                System.out.println("Row: " + treeSource.getSelectionRows()[0]);
            }
        };
        tree.addTreeSelectionListener(treeSelectionListener);
        JFrame frame = new JFrame("JTree With Multi-Discontiguous selection");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(tree));
        frame.setPreferredSize(new Dimension(380, 320));
        frame.setLocation(150, 150);
        frame.pack();
        frame.setVisible(true);
    }

    private TreeWithMultiDiscontiguousSelections() {
    }
}
like image 141
mKorbel Avatar answered Dec 29 '22 13:12

mKorbel


See:

  • setSelectionPaths(TreePath[]) and setSelectionRows(int[]) in the JTree JavaDocs.

  • How to Use Trees in the Java Tutorial.

like image 45
Andrew Thompson Avatar answered Dec 29 '22 14:12

Andrew Thompson