jtree程序化多选 [英] jtree programmatic multi selection

查看:143
本文介绍了jtree程序化多选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以以编程方式在JTree中选择多个树节点? 我已经通过tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_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?

谢谢

推荐答案

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() {
    }
}

这篇关于jtree程序化多选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆