/**
*
*/
package de.tutorials;
import javax.swing.DefaultCellEditor;
import javax.swing.InputVerifier;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.text.JTextComponent;
/**
* @author Tom
*
*/
public class JTableExample extends JFrame {
public JTableExample() {
super("JTableExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTable table = new JTable(buildDummyTableModel()) {
public boolean isCellEditable(int row, int column) {
if (column == 2) {
return !"A".equals(getValueAt(row, 1));
}
return super.isCellEditable(row, column);
}
};
table.getColumnModel().getColumn(1).setCellEditor(
new DefaultCellEditor(new JComboBox(new String[] { "A", "B",
"C" })));
table.getColumnModel().getColumn(3).setCellEditor(
new ValidatingCellEditor(new JTextField(), new InputVerifier() {
public boolean verify(javax.swing.JComponent input) {
String text = ((JTextComponent) input).getText();
if (!text.matches("\\d+")) {
return false;
} else {
int value = Integer.parseInt(text);
boolean validInput = value <= 100;
// System.out.printf(
// "input (%s) is vaild input: %s\n", text,
// validInput);
return validInput;
}
}
}));
add(new JScrollPane(table));
pack();
setVisible(true);
}
private TableModel buildDummyTableModel() {
int i = 1;
Object[][] data = new Object[][] {
{ Integer.valueOf(i++), "B", "Bar" + Math.random(),
Integer.valueOf(i * 10), "Fart" + Math.random() },
{ Integer.valueOf(i++), "C", "Bar" + Math.random(),
Integer.valueOf(i * 10), "Fart" + Math.random() },
{ Integer.valueOf(i++), "B", "Bar" + Math.random(),
Integer.valueOf(i * 10), "Fart" + Math.random() },
{ Integer.valueOf(i++), "C", "Bar" + Math.random(),
Integer.valueOf(i * 10), "Fart" + Math.random() } };
DefaultTableModel dtm = new DefaultTableModel(data, new Object[] {
"Spalte1", "Spalte2", "Spalte3", "Spalte4", "Spalte5" });
return dtm;
}
/**
* @param args
*/
public static void main(String[] args) {
new JTableExample();
}
class ValidatingCellEditor extends DefaultCellEditor {
InputVerifier verifier;
public ValidatingCellEditor(JTextField textField, InputVerifier verifier) {
super(textField);
this.verifier = verifier;
}
public boolean stopCellEditing() {
if (verifier.verify(editorComponent)) {
return super.stopCellEditing();
} else {
return false;
}
}
}
}