格式化Jtable单元格,如果格式不合法,则什么也不做 [英] Format a Jtable Cell, if illegal format, then do nothing

查看:71
本文介绍了格式化Jtable单元格,如果格式不合法,则什么也不做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我的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列中的项目,您可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆