格式化Jtable单元格,如果格式不合法,则什么也不做 [英] Format a Jtable Cell, if illegal format, then do nothing
问题描述
说我的Jtable中有以下几列:
Say I have following columns in my Jtable:
{"Item", "Price"}
我要将价格列的格式设置为"0.00". 但是,如果用户输入了非法字符串,则保留该单元格的原始值. 例如,当价格为"1.23"但用户要输入"abc"时,单元格仍应为"1.23"
I want format the price column to "0.00" format. But if user enter an illegal string, then keep the original value of the cell. ex, when the price is "1.23", but when user want to enter "abc", then the cell should still be "1.23"
我该怎么办?
谢谢
推荐答案
让我们将大问题分解为较小的问题.
Let's split your big problemn into smaller ones.
首先,您希望按照指定的格式显示Price
列中的项目,您可以使用 NumberFormat
以显示正确的小数位数).由于您的表只有两列不同类型的列,所以最简单的解决方案是使用
First, you want to have items of your Price
column to be displayed according to a specified format, which you can achieve using a TableCellRenderer
(which, when rendering numbers, will use a NumberFormat
to display the correct number of decimals). As your table has only two columns of different types, the simplest solution is to use JTable#setDefaultRenderer(Class<?> columnClass, TableCellRenderer renderer)
. This way, your numbers will always be displayed using the correct number of decimals.
Second, for your edition issue, the same solution can be rather elegant : call JTable#setDefaultEditor(java.lang.Class, javax.swing.table.TableCellEditor)
and set as editor a component one that will, before commiting change to your table model, ensure the new value is a valid number (valid of course according to your rules).
这篇关于格式化Jtable单元格,如果格式不合法,则什么也不做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!