我有一个 JTree,我可以(ctrl)选择多个节点。当我右键单击时,我会弹出一个可以选择“刷新”的弹出窗口。(此站点上还有其他问题解释了如何执行此操作)
问题是,当我选择多个节点并右键单击时,只有我右键单击的节点被选中,其他节点被取消选择。
我想选择例如 3 个节点(叶子),右键单击,选择“刷新”并仍然选择这 3 个节点。
有什么建议吗?谢谢!
例子:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class JTreeMultiSelect extends JFrame{
public JTreeMultiSelect() {
super("Test");
JTree myTree = new JTree();
myTree.getSelectionModel()
.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
// add MouseListener to tree
MouseAdapter ma = new MouseAdapter() {
private void myPopupEvent(MouseEvent e) {
int x = e.getX();
int y = e.getY();
JTree tree = (JTree)e.getSource();
TreePath path = tree.getPathForLocation(x, y);
if (path == null)
return;
tree.setSelectionPath(path);
DefaultMutableTreeNode rightClickedNode =
(DefaultMutableTreeNode)path.getLastPathComponent();
if(rightClickedNode.isLeaf()){
JPopupMenu popup = new JPopupMenu();
final JMenuItem refreshMenuItem = new JMenuItem("refresh");
refreshMenuItem.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("refresh!");
}
});
popup.add(refreshMenuItem);
popup.show(tree, x, y);
}
}
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) myPopupEvent(e);
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) myPopupEvent(e);
}
};
myTree.addMouseListener(ma);
JPanel myPanel = new JPanel();
myPanel.add(myTree);
this.add(myPanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new JTreeMultiSelect();
}
}