How Can I Prevent Negative or Zero Values in JTable Cells?
Oct 28, 2024 pm 01:17 PMPreventing Invalid Input in JTable Cells
The JTable component provides built-in validation for certain data types, such as integers. However, it does not handle negative or zero values by default. To implement custom validation rules, you can create a custom cell editor class.
Solution:
Instead of using a TableModel that validates input, create a subclass of DefaultCellEditor as follows:
<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>
This custom editor checks user input and displays a red border for invalid values (negative or zero).
Implementation:
Instantiate the custom editor and set it for the desired column:
<code class="java">JTextField integerField = new JTextField(); PositiveIntegerCellEditor integerEditor = new PositiveIntegerCellEditor(integerField); table.getColumnModel().getColumn(columnIndex).setCellEditor(integerEditor);</code>
This solution mimics the behavior of the default editor for integer input, rejecting negative or zero values and highlighting invalid cells.
The above is the detailed content of How Can I Prevent Negative or Zero Values in JTable Cells?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte

How does Java's classloading mechanism work, including different classloaders and their delegation models?

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?

Node.js 20: Key Performance Boosts and New Features

Iceberg: The Future of Data Lake Tables

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed

How to Share Data Between Steps in Cucumber
