我想仅在JTree
节点上右键单击弹出框,而不是整个JTree
组件。
当用户右键单击JTree节点时,弹出框出现。如果他右键单击JTree
中的空格,则不应该出现。那么为什么我只能检测JTree
节点的鼠标事件。我已经多次搜索网络,但找不到解决方案,所以请帮助我。
感谢。
答案 0 :(得分:13)
这是一个简单的方法:
public static void main ( String[] args )
{
JFrame frame = new JFrame ();
final JTree tree = new JTree ();
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" ) );
menu.show ( tree, pathBounds.x, pathBounds.y + pathBounds.height );
}
}
}
} );
frame.add ( tree );
frame.pack ();
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
答案 1 :(得分:2)
因为我最近偶然发现了这一点,我觉得它比现有的答案容易一点:
public static void main(String[] args) {
JFrame frame = new JFrame();
final JTree tree = new JTree();
JPopupMenu menu = new JPopupMenu();
menu.add(new JMenuItem("Test"));
tree.setComponentPopupMenu(menu);
frame.add(tree);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}