首頁 Java java教程 如何防止 JTable 儲存格中出現負值或零值?

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

Oct 28, 2024 pm 01:17 PM

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。