树控件的选择方式有三种,通过树控件的选择模型TreeSelectionModel对象进行设置,如下:
static int CONTIGUOUS_TREE_SELECTION
选择只能是连续的。
static int DISCONTIGUOUS_TREE_SELECTION
选择可以包含任何数量的不一定连续的项目。
static int SINGLE_TREE_SELECTION
选择一次只能包含一个路径。
对于选择路径TreePath对象,通过getLastPathComponent方法返回路径最后的节点。
通过一个实例,把左边选择的节点添加到右边的树控件中,代码如下:
public class SelectedTree extends JFrame
{
public JTree tree,tree1;
public DefaultTreeModel dtm;
public TreeSelectionModel dtst;
static int index = 0;
JTextField jtf ;
StringBuffer str = new StringBuffer("数论");
public SelectedTree()
{
JPanel panel = new JPanel();
initTree();
JPanel panel1 = new JPanel(new GridLayout(1,2));
panel1.add(tree);
panel1.add(tree1);
add(panel1);
tree.setBorder(new TitledBorder("普通树控件"));
JButton jbn = new JButton("复制选择的节点信息");
jbn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
addNodes(tree.getSelectionPaths());
tree1.updateUI();
}
});
panel.add(jbn);
add(panel, BorderLayout.SOUTH);
init();
}
//递归添加节点
private void addNodes(DefaultMutableTreeNode node, DefaultMutableTreeNode addNode)
{
DefaultMutableTreeNode t1 = new DefaultMutableTreeNode(addNode.getUserObject());
node.add(t1);
if(!addNode.isLeaf())
{
for(int j=0;j<addNode.getChildCount();j++)
addNodes(t1,(DefaultMutableTreeNode)addNode.getChildAt(j));
}
}
private void addNodes(TreePath[] tps)
{
DefaultTreeModel dtm1 = (DefaultTreeModel) tree1.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) dtm1.getRoot();
for(int i=0;i<tps.length;i++)
{
DefaultMutableTreeNode temp = (DefaultMutableTreeNode) tps[i].getLastPathComponent();
DefaultMutableTreeNode t1 = new DefaultMutableTreeNode(temp.getUserObject());
root.add(t1);
if(!temp.isLeaf())
{
for(int j=0;j<temp.getChildCount();j++)
addNodes(t1,(DefaultMutableTreeNode)temp.getChildAt(j));
}
}
}
private void initTree()
{
// TODO Auto-generated method stub
DefaultMutableTreeNode root = new DefaultMutableTreeNode("科学");
DefaultMutableTreeNode shuxue = new DefaultMutableTreeNode("数学");
DefaultMutableTreeNode jisuanji = new DefaultMutableTreeNode("计算机");
root.add(shuxue);
root.add(jisuanji);
addTreeNode(shuxue,new String[] {str.toString(),"几何","代数"});
addTreeNode(jisuanji,new String[] {"编程语言","操作系统","算法"});
tree = new JTree(root);
tree.setEditable(true);
//tree.setDragEnabled(true);
dtst = tree.getSelectionModel();
dtm = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root1 = new DefaultMutableTreeNode("科学");
tree1 = new JTree(root1);
}
private void addTreeNode(DefaultMutableTreeNode parent, String[] strs)
{
for(int i = 0;i<strs.length;i++)
{
DefaultMutableTreeNode temp = new DefaultMutableTreeNode(strs[i]);
parent.add(temp);
}
}
//对树控件进行初始化,例如图标
public void init()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 500);
this.setLocationRelativeTo(null);
this.setTitle("树控件");
this.setVisible(true);
}
}
通过节点添加,需要更新树控件。
运行如下:
由于水平有限,如果有错误,请大家多多指导,提高水平,共同学习。