If you're trying to validate data in a table, you could use something like this class:
import org.apache.log4j.Logger;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* Implements a cell editor that uses a text field to validate and edit Double values.
*/
public class DoubleEditor extends DefaultCellEditor {
private static final Logger log = Logger.getLogger(DoubleEditor.class);
private JTextField textField;
private double min, max;
private static final Color RED_COLOR = new Color(240, 175, 175);
private static final Border BLACK_BORDER = new LineBorder(Color.BLACK);
public DoubleEditor(double min, double max) {
this(new JTextField(), min, max);
}
public DoubleEditor(JTextField jt, double min, double max) {
super(jt);
textField = (JTextField) getComponent();
this.min = min;
this.max = max;
textField.setHorizontalAlignment(JTextField.TRAILING);
textField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "check");
textField.getActionMap().put("check", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
log.debug("text:" + textField.getText());
textField.postActionEvent();
}
});
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JTextField textField = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
textField.setText(value == null ? null : value.toString());
textField.setBackground(Color.WHITE);
textField.setBorder(BLACK_BORDER);
return textField;
}
public Object getCellEditorValue() {
JTextField ftf = (JTextField) getComponent();
return ftf.getText() == null || ftf.getText().trim().equals("") ? null : Double.parseDouble(ftf.getText());
}
/**
* Override to check whether the edit is valid, setting the value if it is and complaining if it isn't. If it's OK
* for the editor to go away, we need to invoke the superclass's version of this method so that everything gets
* cleaned up.
*/
public boolean stopCellEditing() {
JTextField textField = (JTextField) getComponent();
if (textField.getText().trim().equals("")) { // if it's the empty string, set it to null
textField.setText(null);
return super.stopCellEditing();
} else if (textField.getText() == null || isValid(textField.getText())) { // otherwise, if it's valid, set it
textField.setBackground(Color.WHITE);
return super.stopCellEditing();
} else { // otherwise, it's not valid
textField.selectAll();
textField.setBackground(RED_COLOR);
return false;
}
}
private boolean isValid(String text) {
try {
double num = Double.parseDouble(text);
return num >= min && num < max;
} catch (NumberFormatException nfe) {
log.debug("bad number: " + text);
}
return false;
}
}
[ November 15, 2008: Message edited by: J. Noah ]