首頁 > Java > java教程 > 主體

如何驗證 JTable 儲存格中的非正整數輸入?

Mary-Kate Olsen
發布: 2024-10-27 07:08:29
原創
904 人瀏覽過

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

JTable 單元格中的輸入驗證無效

問題:

問題:

考慮一個🎜>其中一列使用getColumnClass() 方法將類別類型指定為Integer。 Swing 會自動標記並拒絕無效輸入(例如雙精度值)。但是,需要對非正整數輸入(負數或零)進行自訂驗證,模仿無效整數輸入的預設行為。

答案:

<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>
登入後複製
與 Swing 不同預設檢查,使用內省來偵測異常,可以使用自訂編輯器進行特定驗證。例如,可以建立 PositiveIntegerCellEditor 作為 DefaultCellEditor 的子類別來完成任務。

在 stopCellEditing() 方法中,嘗試將輸入轉換為 Integer。如果值為非正數,則會拋出 NumberFormatException,導致文字欄位顯示為紅色,表示輸入無效。 當點擊輸入無效的儲存格時,PositiveIntegerCellEditor 將被啟動後,退出編輯模式(例如,按 Enter 或 Tab)後,stopCellEditing() 方法將嘗試轉換輸入。如果轉換失敗(即輸入為非正數),textField 邊框將設定為紅色,並且焦點將保留在儲存格上。

以上是如何驗證 JTable 儲存格中的非正整數輸入?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!