Search code examples
javaswingjtablejtextfield

SetCaretPosition in JTable


How can I set caret position in a JTable?

I know JTextField has setCaretPosition(n) function. But I cannot access JTextField in the JTable.

I would like the Table text caret position equal text length. It is possible to mouseclick event but it should be normal position.

My code:

public class TableTest extends javax.swing.JFrame
{

    public TableTest()
    {
        javax.swing.JTable jTable1 = new javax.swing.JTable();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]
                {
                    {
                        "This is too long text!", "This is too long text!",
                    },
                    {
                        "This is too long text!", "This is too long text!",
                    }
                },
                new String[]
                {
                    "Title 1", "Title 2",
                }
        )); 

        add(jTable1);

        pack();

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setLocationRelativeTo(null);
    }
    public static void main(String args[])
    {
        new TableTest().setVisible(true);
    }

}

This table cells are shown: [This is too...] but it should be [..long text!]


Solution

  • This table cells are shown: [This is too...] but it should be [..long text!]

    This the renderer that displays the text in a cell. The default renderer is a JLabel and it will display ... when the text is truncated. If you want the ... at the start of the cell then you need to create a custom renderer.

    Check out the Left Dot Renderer for a renderer that does this.