首頁  >  文章  >  Java  >  如何防止 JTable 儲存格中出現負值或零值?

如何防止 JTable 儲存格中出現負值或零值?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-28 13:17:02462瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn