如何雙擊JTree節點並獲取其名稱?雙擊JTree節點並獲取其名稱
如果我打電話給evt.getSource()
看來返回的對象是JTree。我不能將它轉換爲DefaultMutableTreeNode。
如何雙擊JTree節點並獲取其名稱?雙擊JTree節點並獲取其名稱
如果我打電話給evt.getSource()
看來返回的對象是JTree。我不能將它轉換爲DefaultMutableTreeNode。
如果你有興趣在檢測節點上無論是雙擊事件,或當 用戶點擊,不管它是否被選中, 我們建議您做以下:
final JTree tree = ...;
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1) {
if(e.getClickCount() == 1) {
mySingleClick(selRow, selPath);
}
else if(e.getClickCount() == 2) {
myDoubleClick(selRow, selPath);
}
}
}
};
tree.addMouseListener(ml);
爲了充分利用節點TreePath
你可以步行路徑或簡單地說,你的情況,使用TreePath#getLastPathComponent
。
這會返回一個Object
,因此您需要自行退回到所需的節點類型。
是的。我知道這一點。但我如何使用selRow和selPath? –
那麼你需要做的下一件事是閱讀['TreePath']的API條目(http://docs.oracle.com/javase/7/docs/api/javax/swing/tree/TreePath.html) – MadProgrammer
MadProgrammer幾乎涵蓋了一切。要獲得對象,您可以撥打
DefaultMutableTreeNode selectedNode =
((DefaultMutableTreeNode)selPath.getLastPathComponent()).
getUserObject();
也許我們應該使用它作爲對象,然後施放: 'Object selectedNode =((DefaultMutableTreeNode)selPath.getLastPathComponent())。getUserObject();' – dannyxyz22
我的示例。我們可以延遲檢測雙擊。
public class TreeListener extends MouseAdapter{
private JTree _Tree;
private boolean singleClick = true;
private int doubleClickDelay = 300;
private Timer timer;
public TreeListener(JTree tree)
{
this._Tree = tree;
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
timer.stop();
if (singleClick) {
singleClickHandler(e);
} else {
try {
doubleClickHandler(e);
} catch (ParseException ex) {
Logger.getLogger(ex.getMessage());
}
}
}
};
timer = new javax.swing.Timer(doubleClickDelay, actionListener);
timer.setRepeats(false);
}
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
singleClick = true;
timer.start();
} else {
singleClick = false;
}
}
private void singleClickHandler(ActionEvent e) {
System.out.println("-- single click --");
}
private void doubleClickHandler(ActionEvent e) throws ParseException {
System.out.println("-- double click -- id=");
}
}
以下代碼適用於我。
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
// Cast nodeInfo to your object and do whatever you want
}
}
});
你能告訴我們一些代碼嗎? –