如何在应用 MaskFormatter 后使 JTable 单元格中的插入符显示在左侧

use*_*339 2 java swing jtable caret jformattedtextfield

将 MaskFormatter 应用到 JFormattedTextField 上,然后将该文本字段设置为 JTable 中的一列后,无论我单击什么位置,插入符号都开始出现。但是,我希望插入符号出现在单元格的最左侧位置,无论用户单击单元格中的哪个位置。我尝试了 setCaretPositionMethod,但它什么也没做。我的猜测是,有某种表侦听器,它强制插入符移动到用户单击的位置,如果我知道这个侦听器是什么,我可以覆盖该功能。

SSCCE:

public class TableExample extends JFrame {
    public TableExample() {
        add(makeTable());
    }

    private JTable makeTable() {
        Object[][] tableData = {{"","a","b",""}, {"","c","d",""}};
        String[] columns = {"column1", "column2", "column3", "dobColumn"};
        JTable table = new JTable(tableData, columns);

        ////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);
        }

        ////Does nothing
        tf.setCaretPoisition(0);

        dobColumn.setCellEditor(new DefaultCellEditor(tf));

        return table;
    }

    public static void main(String[] args) {
        JFrame frame = new TableExample();
        frame.setSize( 300, 300 );
        frame.setVisible(true); 
    }
}
Run Code Online (Sandbox Code Playgroud)

cam*_*ckr 5

如果我没记错的话,您可以将 a 添加FocusListener到格式化文本字段,然后当组件获得焦点时,您可以调用该setCaretPosition(0)方法。

但是,此语句必须包含在 a 中SwingUtilities.invokeLater(...),以确保在格式化文本字段的默认插入符号定位之后执行代码。

另一个选项是重写isCellEditable(...)JTable 的方法。然而,这种方法将影响表中的所有编辑器。

以下示例代码展示了如何在调用编辑器时“选择”文本:

public boolean editCellAt(int row, int column, EventObject e)
{
    boolean result = super.editCellAt(row, column, e);
    final Component editor = getEditorComponent();

    if (editor != null && editor instanceof JTextComponent)
    {
        ((JTextComponent)editor).selectAll();

        if (e == null)
        {
            ((JTextComponent)editor).selectAll();
        }
        else if (e instanceof MouseEvent)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    ((JTextComponent)editor).selectAll();
                }
            });
        }

    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)