首页  >  文章  >  Java  >  如何验证 JTable 单元格中的非正整数输入?

如何验证 JTable 单元格中的非正整数输入?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-27 07:08:29904浏览

How to Validate Non-Positive Integer Input in JTable Cells?

JTable 单元格中的输入验证无效

问题:

考虑一个 JTable,其中一列使用 getColumnClass() 方法将类类型指定为 Integer。 Swing 自动标记并拒绝无效输入(例如双精度值)。但是,需要对非正整数输入(负数或零)进行自定义验证,模仿无效整数输入的默认行为。

答案:

与 Swing 不同默认检查,使用内省来检测异常,可以使用自定义编辑器进行特定验证。例如,可以创建 PositiveIntegerCellEditor 作为 DefaultCellEditor 的子类来完成任务。

在 stopCellEditing() 方法中,尝试将输入转换为 Integer。如果值为非正数,则会抛出 NumberFormatException,导致文本字段显示为红色,表示输入无效。

<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;
        this.textField.setHorizontalAlignment(JTextField.RIGHT);
    }

    @Override
    public boolean stopCellEditing() {
        try {
            int v = Integer.valueOf(textField.getText());
            if (v < 0) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            textField.setBorder(red);
            return false;
        }
        return super.stopCellEditing();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table,
        Object value, boolean isSelected, int row, int column) {
        textField.setBorder(black);
        return super.getTableCellEditorComponent(
            table, value, isSelected, row, column);
    }
}</code>

当单击输入无效的单元格时,PositiveIntegerCellEditor 将被激活后,退出编辑模式(例如,按 Enter 或 Tab)后,stopCellEditing() 方法将尝试转换输入。如果转换失败(即输入为非正数),textField 边框将设置为红色,并且焦点将保留在单元格上。

以上是如何验证 JTable 单元格中的非正整数输入?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn