java JTable如何触发选择一行或双击一行的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27742534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JTable how to fire event selecting a row or double click on a row
提问by insilenzio
I'm using a javax.swing.JTable to show rows in a database table. I need to fire two different event for two different cases:
我正在使用 javax.swing.JTable 来显示数据库表中的行。我需要为两种不同的情况触发两个不同的事件:
- when is selected at least a row (or a click on at least a row is performed).
- when a double click on a row is performed.
- 何时选择至少一行(或单击至少一行)。
- 当双击一行时。
I already looked for an answer on stack overflow, but I didn't find anything satisfying . Any idea?
我已经在寻找堆栈溢出的答案,但没有找到任何令人满意的答案。任何的想法?
回答by MadProgrammer
when is selected at least a row (or a click on at least a row is performed).
何时选择至少一行(或单击至少一行)。
You should monitor changes to the row selection using the JTable
s ListSelectionModel
via a ListSelectionListener
. This will notify you when the selection is changed by the user using the mouse or the keyboard or if the selection is changed programmatically for some reason
您应该使用JTable
sListSelectionModel
通过 a监视对行选择的更改ListSelectionListener
。这将在用户使用鼠标或键盘更改选择时或由于某种原因以编程方式更改选择时通知您
See How to Write a List Selection Listenerfor more details
有关更多详细信息,请参阅如何编写列表选择侦听器
when a double click on a row is performed
双击一行时
The only way you can detect this is through a use of a MouseListener
. Normally, users expect that a left mouse button click will do one action and the right mouse button will do something else.
您可以检测到这一点的唯一方法是使用MouseListener
. 通常,用户希望鼠标左键单击执行一个操作,而鼠标右键单击执行其他操作。
You will want to use SwingUtilities.isLeftMouseButton
or SwingUtilities.isRightMouseButton
to determine what the user is actually doing.
您将想要使用SwingUtilities.isLeftMouseButton
或SwingUtilities.isRightMouseButton
确定用户实际在做什么。
See How to Write a Mouse Listenerfor more details
有关更多详细信息,请参阅如何编写鼠标侦听器
回答by eatSleepCode
You can add a mouse listener to the table and capture event over there with mouse event like below
您可以向表中添加一个鼠标侦听器并使用如下鼠标事件捕获那里的事件
table.addMouseListener
(
new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2)
{
}
if (e.getClickCount() == 1)
{
}
}
}
);
}
and to capture selection event you can use
并捕获您可以使用的选择事件
table.getSelectionModel().addListSelectionListener(...);