Swing:一列的多个单元格编辑器
在我的 JTable 中,我有两个可编辑的数字列。两列的编辑器都扩展了 AbstractCellEditor 并使用 JFormattedTextField 作为编辑组件。
问题在于输入的格式取决于行中另一列的值。如果满足条件X,则小数位数应为Y,否则应为Y+2。
我尝试重写 getTableCellEditor(..) 方法来关联每行一个 TableCellEditor。请参阅此示例。但是,由于我有两个可编辑列,因此每行共享一个 TableCellEditor 对象会产生一些非常奇怪的结果。我认为这不是一个合适的解决方案。
任何关于如何解决这个问题的想法将不胜感激!
谢谢你!
In my JTable, I have two editable numeric columns. The editor for both columns extends AbstractCellEditor and uses a JFormattedTextField as an the editing component.
The problem is that the format for input depends on the value of another column in the row. If condition X is met, the number of fraction digits should be Y, otherwise they should be Y+2.
I attempted to override the getTableCellEditor(..) method to associate a TableCellEditor per row. See this example. However, since I have two editable columns, sharing a single TableCellEditor object per row gives some very odd results. I don't think this is an appropriate solution.
Any ideas on how to approach this would be much appreciated!
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您不需要为每行关联一个 TableCellEditor。
你只需要一个,它会自己访问其他数据。在 getTableCellEditor() 中,您可以访问表格以及坐标(列、行)。
这样,您可以直接向表询问当前行所需列的值。
请记住,与渲染器一样,单元格编辑器是“共享的”。您确实要求同一个对象为您提供编辑器组件(大多数情况下是 TableCellEditor 本身,例如扩展 JFormattedTextField)。因此,您不需要每行放置一个,将使用当前列和行索引调用方法
getTableCellEditor()
,并且您将提供具有适当格式的组件,具体取决于条件..是这样的:
I don't think you need to associate a TableCellEditor per row.
You only need one , which will access other data by himself. in the getTableCellEditor(), you have access to the table, as well as the coordinates (column, row).
With this, you can ask directly the table for its value at the wanted column, for the current row.
Keep in mind that like renderers, cell editors are "shared". You are indeed asking the same object to provide you the editor component (which is most of the time the
TableCellEditor
itself, extending aJFormattedTextField
, for example). So you don't need to put one per row, the methodgetTableCellEditor()
will be called, with the current column and row indexes, and you will provide the component, with the appropriate format, depending on the condition..Something like this:
您可以通过创建另一个 TableCellEditor 来解决这个问题,它将委托给它的两个分包商之一:当前单元格编辑器的实例。您需要向列注册这个 uber-celleditor,并让它在 Swing 使用时进行委托。
You can solve it by creating yet another TableCellEditor which will delegate to either of its two subcontractors: the instances of your current cell editors. You need to register this uber-celleditor with the column and let it delegate whenever it is used by Swing.
我将重写 JTable 的 getCellEditor(...) 方法。然后您可以根据数据的格式返回适当的编辑器。
I would override the getCellEditor(...) method of JTable. Then you can return the appropriate editor based on the format of the data.