使用JTree列出对象

时间:2017-12-02 17:10:04

标签: java swing jtree

目前我正在尝试学习Swing。我希望JTree与我的ArrayList一起制作Object个实例。每个对象都有一个名称,我希望能够通过右键单击然后出现更改按钮来更改该名称。但我真的不明白Mouselistener。我用Google搜索并获得了鼠标监听器,但我不知道如何添加setName方法。

Lager是我的示例对象。 400是容量。

private DefaultMutableTreeNode createTree() {
    Lager s = new Lager("Name",400);
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(s);
    DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode("Vegetables");
    DefaultMutableTreeNode fruitNode = new DefaultMutableTreeNode("Fruits");
    // add the child nodes to the root node
    root.add(vegetableNode);
    root.add(fruitNode);
    return root;
}

这是我复制的鼠标监听器。

    DefaultMutableTreeNode root = createTree();

    JTree tree = new JTree(root);

    tree.addMouseListener ( new MouseAdapter ()
    {
        public void mousePressed ( MouseEvent e )
        {
            if ( SwingUtilities.isRightMouseButton ( e ) )
            {
                TreePath path = tree.getPathForLocation ( e.getX (), e.getY () );
                Rectangle pathBounds = tree.getUI ().getPathBounds ( tree, path );
                if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) )
                {
                    JPopupMenu menu = new JPopupMenu ();
                    menu.add ( new JMenuItem ( "Test" ) );
                    System.out.println(tree.getLastSelectedPathComponent());
                    menu.show ( tree, pathBounds.x, pathBounds.y + pathBounds.height ); // pathBounds.y/x sind die Positionen des Lagers auf den ich Rechtsklicke
                }
            }
        }
    } );

    this.add(tree);

0 个答案:

没有答案