首页 > Java > java教程 > 正文

如何防止 JTable 单元格中出现负值或零值?

Mary-Kate Olsen
发布: 2024-10-28 13:17:02
原创
472 人浏览过

How Can I Prevent Negative or Zero Values in JTable Cells?

防止 JTable 单元格中的无效输入

JTable 组件为某些数据类型(例如整数)提供内置验证。但是,默认情况下它不处理负值或零值。要实现自定义验证规则,您可以创建自定义单元格编辑器类。

解决方案:

不要使用验证输入的 TableModel,而是创建 DefaultCellEditor 的子类作为如下所示:

<code class="java">private static class PositiveIntegerCellEditor extends DefaultCellEditor {

    private static final Border red = new LineBorder(Color.red);
    private static final Border black = new LineBorder(Color.black);
    private JTextField textField;

    public PositiveIntegerCellEditor(JTextField textField) {
        super(textField);
        this.textField = textField;
        textField.setHorizontalAlignment(JTextField.RIGHT); // Align right for positive numbers
    }

    @Override
    public boolean stopCellEditing() {
        try {
            int value = Integer.valueOf(textField.getText());
            if (value < 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            textField.setBorder(red); // Highlight invalid input
            return false;
        }
        textField.setBorder(black); // Reset border for valid input
        return super.stopCellEditing();
    }
}</code>
登录后复制

此自定义编辑器检查用户输入,并为无效值(负数或零)显示红色边框。

实现:

实例化自定义编辑器并将其设置为所需的列:

<code class="java">JTextField integerField = new JTextField();
PositiveIntegerCellEditor integerEditor = new PositiveIntegerCellEditor(integerField);
table.getColumnModel().getColumn(columnIndex).setCellEditor(integerEditor);</code>
登录后复制

此解决方案模仿整数输入的默认编辑器的行为,拒绝负值或零值并突出显示无效单元格。

以上是如何防止 JTable 单元格中出现负值或零值?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!