gpt4 book ai didi

java - 将 MaskFormatter 应用于 JTable 中的列,但掩码仅用于我在该列中编辑的第一个单元格

转载 作者:行者123 更新时间:2023-12-01 09:24:47 27 4
gpt4 key购买 nike

////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 列的单元格编辑器设置为带有掩码,掩码仅应用于我在列中单击的第一个单元格。

编辑:这是我的 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);
}

}

最佳答案

我仍然不确定为什么每次单击 dobColumn 内的单元格时 Mask 都会被破坏。因此,我决定实现 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));
}
}

关于java - 将 MaskFormatter 应用于 JTable 中的列,但掩码仅用于我在该列中编辑的第一个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39926784/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com