我需要幫助有關的JTree和JPopupMenu的靈氣行爲。我正在給JTree設置一個右鍵菜單。如果我打開右鍵菜單後,左鍵單擊一個節點與另一個節點,點擊節點成爲選擇。但在靈動的外觀和感覺上,需要第二次點擊來選擇另一個節點。我的代碼如下,你可以用默認的外觀和感覺來評論nimbus部分。改變靈氣JPopupMenu的行爲
public class JTreeDemo {
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception ex) {
}
}
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
rootNode.add(new DefaultMutableTreeNode("Child1"));
rootNode.add(new DefaultMutableTreeNode("Child2"));
rootNode.add(new DefaultMutableTreeNode("Child3"));
DefaultTreeModel model = new DefaultTreeModel(rootNode);
JTree tree = new JTree(model);
tree.addMouseListener(new TreeMouseListener());
JFrame jf = new JFrame();
jf.getContentPane().add(new JScrollPane(tree));
jf.setSize(new Dimension(300, 300));
jf.setVisible(true);
}
}
class TreeMouseListener extends MouseAdapter {
@Override
public void mouseReleased(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)) {
JTree tree = (JTree) e.getSource();
TreePath jClickedPath = tree.getPathForLocation(e.getX(), e.getY());
tree.setSelectionPath(jClickedPath);
JPopupMenu menu = new JPopupMenu();
menu.add(new JMenuItem("menu1"));
menu.show(tree, e.getX(), e.getY());
}
}
}
[覆蓋JTree中的getPopupLocation](http://stackoverflow.com/a/8082241/714968),btw適用於Java 8和Nimbus L&F中的1.st鼠標事件。 – mKorbel