Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark JTable cell input as invalid?

If I take a JTable and specify a column's classtype on it's model as follows:

   DefaultTableModel model = new DefaultTableModel(columnNames, 100) {
       @Override
        public Class<?> getColumnClass(int columnIndex) {
            return Integer.class;
        }};

Then whenever a user tries to enter a double value into the table, Swing automatically rejects the input and sets the cell's outline to red.

I want the same effect to occur when someone enters a 'negative or 0' input to the cell. I've got this:

    @Override
    public void setValueAt(Object val, int rowIndex, int columnIndex) {
       if (val instanceof Number && ((Number) val).doubleValue() > 0) {
              super.setValueAt(val, rowIndex, columnIndex);
            } 
       }
   }

This prevents the cell from accepting any non-positive values, but it doesn't set the color to red and leave the cell as editable.

I tried looking into how JTable's doing the rejection by default, but I can't seem to find it.

How can I make it reject the non-positive input the same way it rejects the non-Integer input?

like image 517
Cuga Avatar asked Sep 23 '11 15:09

Cuga


1 Answers

This code is a small improvement of the accepted answer. If the user does not enter any value, clicking on another cell should allow him to select another cell. The accepted solution does not allow this.

@Override
public boolean stopCellEditing() {

    String text = field.getText();

    if ("".equals(text)) {
        return super.stopCellEditing();
    }

    try {
        int v = Integer.valueOf(text);

        if (v < 0) {
            throw new NumberFormatException();
        }            
    } catch (NumberFormatException e) {

        field.setBorder(redBorder);
        return false;
    }

    return super.stopCellEditing();
}

This solution checks for empty text. In case of an empty text, we call the stopCellEditing() method.

like image 130
Jan Bodnar Avatar answered Oct 14 '22 15:10

Jan Bodnar