Java JTable 的任何单元格中的更改的正确事件是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2062409/
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
Whats the proper event for changes in any cell of JTable?
提问by Sejanus
I have a simple JTable, there are two columns that matter: quantity and value (Integers). Each time user enters a new row or updates one, each rows value must be multiplied by quantity, results sumed together and the result sum displayed in a JLabel outside the JTable. Looks pretty simple. Except that I have no idea what event should I look for. Something like "cell value changed"? When I right click on the JTable in NetBeans I see no such event or dont recognize it ;) Anyway, before I come up with some weird noobish solution I thought I might ask here what's the proper way to do it :)
我有一个简单的 JTable,有两列很重要:数量和值(整数)。每次用户输入新行或更新一行时,每行值必须乘以数量,结果相加,结果总和显示在 JTable 外的 JLabel 中。看起来很简单。除了我不知道我应该寻找什么事件。诸如“单元格值已更改”之类的东西?当我右键单击 NetBeans 中的 JTable 时,我看不到这样的事件或不认识它;) 无论如何,在我想出一些奇怪的 noobish 解决方案之前,我想我可能会在这里问什么是正确的方法:)
采纳答案by pstanton
you should add a TableModelListeneras described here.
您应该按照此处所述添加TableModelListener。
also, in your listener once you've updated the value of the other cell values programatically you will need to call model.fireTableCellUpdated
to let swing know about the changes
此外,在您的侦听器中,一旦您以编程方式更新了其他单元格值的值,您将需要调用model.fireTableCellUpdated
让 Swing 知道这些更改
回答by Sejanus
Finally I managed to find how to do it in NetBeans with all the code protection, et cetera. It's right click on JTable in Design View, Properties, then Code tab, and then add your code in Pre-Adding Code section (code evaluated before table is added to container or something like that).
最后,我设法找到了如何在 NetBeans 中使用所有代码保护等进行操作。在“设计视图”、“属性”、“代码”选项卡中右键单击 JTable,然后在“预添加代码”部分(在将表添加到容器或类似内容之前评估的代码)中添加您的代码。
The exact code which works for me is this:
对我有用的确切代码是这样的:
table.getModel().addTableModelListener(
new TableModelListener()
{
public void tableChanged(TableModelEvent evt)
{
// here goes your code "on cell update"
}
});
I am aware that Tom, above, suggested never calling getModel() but I'm too new to Java to understand why (care to explain, please..?) :) and it's just an example anyway, I'm adding this answer just to show howto do it in NetBeans (thanks pstanton for answering whatto do). Because I found so many people asking this in internet and no real answers (apart from "copy your protected code out of NetBeans protected area and then customize your table).
我知道上面的汤姆建议永远不要调用 getModel() 但我对 Java 太陌生了,无法理解为什么(请解释一下,请..?):) 无论如何这只是一个例子,我正在添加这个答案只是为了展示如何在 NetBeans 中做到这一点(感谢 pstanton 回答要做什么)。因为我发现互联网上有很多人在问这个问题,但没有真正的答案(除了“将受保护的代码复制到 NetBeans 保护区外,然后自定义表)。