java 检测 JTable 中的选择更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5453367/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:11:43  来源:igfitidea点击:

Detecting Selection Changes in a JTable

javaswingjtable

提问by Jonathan

I'm trying to find a way to detect changes in which column the user selected in a JTable. I did some poking around and it appears that you need to somehow use a TableColumnModelListener in order to detect the changes, but that doesn't seem to fire an event when you change the column you have selected.

我试图找到一种方法来检测用户在 JTable 中选择的列的变化。我做了一些探索,似乎您需要以某种方式使用 TableColumnModelListener 来检测更改,但是当您更改所选列时,这似乎不会触发事件。

回答by jzd

You need to add a ListSelectionListenerinstead. That will capture selection events. Here are some Swing tutorials that go further in depth:

您需要添加一个ListSelectionListener。这将捕获选择事件。以下是一些更深入的 Swing 教程:

http://download.oracle.com/javase/tutorial/uiswing/events/listselectionlistener.htmlhttp://download.oracle.com/javase/tutorial/uiswing/components/table.html#selection

http://download.oracle.com/javase/tutorial/uiswing/events/listselectionlistener.html http://download.oracle.com/javase/tutorial/uiswing/components/table.html#selection

回答by Boro

From what I read, I think you need to add a MouseListener to your table, which for example in mouseClicked will get the row and column using the following code, below:

根据我的阅读,我认为您需要在表中添加一个 MouseListener ,例如在 mouseClicked 中将使用以下代码获取行和列,如下所示:



table.addMouseListener(new MouseListener()
{
    @Override
    public void mouseClicked(MouseEvent e)
    {   
       Point pnt = evt.getPoint();
       int row = table.rowAtPoint(pnt);
       int col = table.columnAtPoint(pnt);
    }
}

It should work great for you I have used similar thing myself before. BTW it look similar to the problem I found on coderanch, link: http://www.coderanch.com/t/332737/GUI/java/detect-single-click-any-cell

它应该对你很有用,我自己以前也用过类似的东西。顺便说一句,它看起来类似于我在 coderanch 上发现的问题,链接:http: //www.coderanch.com/t/332737/GUI/java/detect-single-click-any-cell

Good luck, Boro

祝你好运,波罗

回答by Enrique

If by "change" you mean changing the value of a cell then you can use an AbstractTableModeland implement the fireTableCellUpdatedmethod

如果“更改”是指更改单元格的值,那么您可以使用AbstractTableModel并实现fireTableCellUpdated方法