我有代碼taken from here,它允許通過單擊行上的任何位置來選擇JTree行。它在單行選擇模式下工作正常。但是,我不知道如何修改它以處理多行選擇。當用戶進行多重選擇時(例如在按住鼠標左鍵的同時按住shift鍵或控制鍵),如何區分這種情況?JTree通過單擊行上的任意位置來選擇節點
import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; @SuppressWarnings("serial") public class NavTree extends JTree { private boolean fWholeRowSelectionEnabled; private MouseListener fRowSelectionListener; final NavTree fThis; public NavTree(TreeNode rootNode) { super(rootNode); fThis = this; init(); } public NavTree() { fThis = this; init(); } private void init() { //setCellRenderer(new NavTreeCellRenderer()); fRowSelectionListener = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { int closestRow = fThis.getClosestRowForLocation( e.getX(), e.getY()); Rectangle closestRowBounds = fThis.getRowBounds(closestRow); if(e.getY() >= closestRowBounds.getY() && e.getY() < closestRowBounds.getY() + closestRowBounds.getHeight()) { if(e.getX() > closestRowBounds.getX() && closestRow < fThis.getRowCount()){ fThis.setSelectionRow(closestRow); } } else fThis.setSelectionRow(-1); } } }; setWholeRowSelectionEnabled(true); } public void setWholeRowSelectionEnabled(boolean wholeRowSelectionEnabled) { fWholeRowSelectionEnabled = wholeRowSelectionEnabled; if (fWholeRowSelectionEnabled) addMouseListener(fRowSelectionListener); else removeMouseListener(fRowSelectionListener); } public boolean isWholeRowSelectionEnabled() { return fWholeRowSelectionEnabled; } public static void main(String[] args) { JFrame frame = new JFrame(); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); root.add(new DefaultMutableTreeNode("Child 1")); root.add(new DefaultMutableTreeNode("Child 2")); root.add(new DefaultMutableTreeNode("Child 3")); NavTree tree = new NavTree(root); frame.add(tree); frame.setSize(200, 300); frame.setVisible(true); } }
感謝先刪除它,並添加它,但它是一個有點依賴於平臺的,有沒有更好的辦法? – user881480
只有平臺依賴於它需要帶鍵盤的平臺...... – Tharwen