问题
////DOB column formats to dd/mm/yy
TableColumn dobColumn = table.getColumnModel().getColumn(3);
DateFormat df = new SimpleDateFormat("dd/mm/yy");
JFormattedTextField tf = new JFormattedTextField(df);
tf.setColumns(8);
try {
MaskFormatter dobMask = new MaskFormatter("##/##/##");
dobMask.setPlaceholderCharacter('0');
dobMask.install(tf);
} catch (ParseException ex) {
Logger.getLogger(DisplayStudents.class.getName()).log(Level.SEVERE, null, ex);
}
dobColumn.setCellEditor(new DefaultCellEditor(tf));
I've followed a similar process to turn cells in a column into ComboBoxes or CheckBoxes and all cells inside those columns have been set to ComoboBoxes/CheckBoxes, but when I set the cell editor for the DOB column to a JFormattedTextField with a mask, the mask is only applied to the first cell I click on in the column.
EDIT: Here's my SSCCE:
public class TableExample extends JFrame {
public TableExample() {
add(makeTable());
}
private JTable makeTable() {
Object[][] tableData = {{"","a","b",""}, {"","c","d",""}};
String[] columns = {"comboBox column", "column2", "column3", "dobColumn"};
JTable table = new JTable(tableData, columns);
////turn into a combo box
TableColumn comboColumn = table.getColumnModel().getColumn(0);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("1st");comboBox.addItem("2nd");
comboColumn.setCellEditor(new DefaultCellEditor(comboBox));
////DOB column formats to dd/mm/yy
TableColumn dobColumn = table.getColumnModel().getColumn(3);
DateFormat df = new SimpleDateFormat("dd/mm/yy");
JFormattedTextField tf = new JFormattedTextField(df);
tf.setColumns(8);
try {
MaskFormatter dobMask = new MaskFormatter("##/##/##");
dobMask.setPlaceholderCharacter('0');
dobMask.install(tf);
} catch (ParseException ex) {
Logger.getLogger(TableExample.class.getName()).log(Level.SEVERE, null, ex);
}
dobColumn.setCellEditor(new DefaultCellEditor(tf));
return table;
}
public static void main(String[] args) {
JFrame frame = new TableExample();
frame.setSize( 300, 300 );
frame.setVisible(true);
}
}
回答1:
I'm still unsure as to why the Mask is destroyed everytime I click a cell inside the dobColumn. So I decided to implement the tableChange method, to recreate the mask whenever a change occurs in the dobColumn
public void tableChanged(TableEvent e) {
if(e.getColumn() == 3) { //if column edited was the dobColumn
System.out.println("Remaking mask");
JFormattedTextField tf = new JFormattedTextField();
try {
MaskFormatter dobMask = new MaskFormatter("##-##-##");
dobMask.setPlaceholderCharacter('0');
dobMask.install(tf);
} catch (ParseException ex) {
Logger.getLogger(DisplayStudents.class.getName()).log(Level.SEVERE, null, ex);
}
table.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(tf));
}
}
来源:https://stackoverflow.com/questions/39926784/applying-a-maskformatter-to-a-column-in-my-jtable-but-the-mask-is-only-used-on