[英]Is there a good way to detect a (double) mouse click on the border between JTable columns?
当我的用户双击列的右边框时,我想实现调整列大小的通用功能。 我遇到的问题是检测到他点击了那里。
我们有确定鼠标 position 的列和行的方法,但我没有找到任何帮助确定 cursor 被单击列之间的边界的方法。 我想我可以得到 cursor 的 position 相对于表格原点,然后使用行的宽度等来确定 Z1791A97A8403730EE0760489A2AEB992 是否是边界代码之一,目的。 UI 运行时中的某些内容知道 cursor 位于该边界上,因为当 cursor 移过边界时,它会更改 cursor 的形状。
我试过这个:
JTableHeader tableHeader = table.getTableHeader();
tableHeader.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent mouseEvent)
{
int modifiers = mouseEvent.getModifiers();
int modifiersX = mouseEvent.getModifiersEx();
int row = table.rowAtPoint(mouseEvent.getPoint());
int col = table.columnAtPoint(mouseEvent.getPoint());
System.out.printf("m1 %x, m2 %x, row/col %d,%d%n", modifiers, modifiersX, row, col);
}
}
);
但是无论我是否点击边框,修饰符和扩展修饰符都是相同的,所以这些对这个没有帮助。
那么如何询问系统鼠标点击是否在边框上,而不必每次计算边框的position?
如果我理解正确,您要检查的是鼠标是否位于 JTable 列 header 边框上?
你已经提到的事情是,如果 cursor 在边界上,它会改变它的形状。 我实际上没有看到出于您的目的使用该功能的任何缺点。
那么,为什么不在表 header mouselistener 中的mouseClicked()
事件中简单地检查当前的 cursor 呢?
快速演示:
public static void main(String args[]) {
Test t = new Test();
SwingUtilities.invokeLater(() -> {
t.buildGui();
});
}
void buildGui() {
JFrame frame = new JFrame();
String[] header = { "col1", "col2" };
Object[][] data = { { "data1", "data2" } };
JTable table = new JTable(data, header);
table.getTableHeader().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (table.getTableHeader().getCursor().getType() == Cursor.E_RESIZE_CURSOR) {
if (e.getClickCount() == 2 && !e.isConsumed()) {
e.consume();
System.out.println("Double click on border!");
}
}
}
});
JScrollPane pane = new JScrollPane(table);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
mouseClicked()
上,检查 cursor 是否是“调整大小光标”。我对此进行了测试,它似乎没有任何缺点。 可能不是最漂亮的解决方案,但我现在想不出更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.