gpt4 book ai didi

java - 检测 JTree 行上的双击

转载 作者:太空宇宙 更新时间:2023-11-04 06:15:42 26 4
gpt4 key购买 nike

我向 JTree 添加一个鼠标监听器,如下所示:

 trProjects.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int selRow = trProjects.getRowForLocation(e.getX(), e.getY());
TreePath selPath = trProjects.getPathForLocation(e.getX(), e.getY());
if(selRow != -1 && e.getClickCount() == 2 && selPath != null) {
Object selectedNode = selPath.getLastPathComponent();
// do something else
}
}
});

这会检测用户是否双击 JTree 的图标或文本。但我希望它还可以检测用户是否单击该行中的其他任何位置。

为了说明我的问题,我做了一个屏幕截图:

visualization of the problem

如何检测行右侧的双击?

最佳答案

不确定它是否适用于所有外观,但您可以尝试覆盖XXXTreeUI#getPathBounds(...):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.plaf.synth.SynthTreeUI;

public final class DoubleClicksOnRightSideRowTest {
private JComponent makeUI() {
final JTree trProjects = new JTree();
trProjects.setUI(new SynthTreeUI() {
@Override public Rectangle getPathBounds(JTree tree, TreePath path) {
if (tree != null && treeState != null) {
Rectangle rect = treeState.getBounds(path, new Rectangle());
if (rect != null) {
Insets insets = tree.getInsets();
rect.width = tree.getWidth();
rect.y += insets.top;
}
return rect;
}
return null;
}
});
trProjects.addMouseListener(new MouseAdapter() {
@Override public void mousePressed(MouseEvent e) {
int selRow = trProjects.getRowForLocation(e.getX(), e.getY());
TreePath selPath = trProjects.getPathForLocation(e.getX(), e.getY());
if (selRow != -1 && e.getClickCount() == 2 && selPath != null) {
Object selectedNode = selPath.getLastPathComponent();
System.out.println("do something else");
}
}
});
return new JScrollPane(trProjects);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new DoubleClicksOnRightSideRowTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

关于java - 检测 JTree 行上的双击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28127683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com