#java #swing #jtable #jformattedtextfield #maskformatter
#java #swing #jtable #jformattedtextfield #maskformatter
Вопрос:
////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));
Я следовал аналогичному процессу, чтобы превратить ячейки в столбце в выпадающие списки или флажки, и для всех ячеек внутри этих столбцов были установлены сопутствующие ящики / флажки, но когда я устанавливаю в редакторе ячеек для столбца DOB значение JFormattedTextField с маской, маска применяется только к первой ячейке, на которую я нажимаюв столбце.
РЕДАКТИРОВАТЬ: вот мой 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'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,
— согласен, так оно и должно работать. Опубликуйте свой SSCCE , который демонстрирует проблему.
Ответ №1:
Я все еще не уверен, почему маска уничтожается каждый раз, когда я нажимаю на ячейку внутри dobColumn . Поэтому я решил реализовать метод tableChange, чтобы воссоздавать маску всякий раз, когда в 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));
}
}