3

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!]

  • 1
    for better help sooner post an SSCCE / MCVE, short, runnable, compilable with hardcoded value for JTable / XxxTableModel in local variables, otherwise everything is about pure guessing, hint - question in this form isn't answerable here – mKorbel Jun 27 '16 at 11:45
  • Thanks, i improve my question. – Halil İbrahim Oymacı Jun 27 '16 at 11:59
  • 1
    @mKorbel: Thank you for critical review. Based on the updated question, I've suggested another approach below. – trashgod Jun 27 '16 at 15:58

2 Answers2

3

The default "startEditing" action, suggested here, is provided by BasicTableUI. It typically selects all the text, which you want to avoid. You can invoke setCaretPosition() in a custom Action bound to your preferred keystroke. The example below uses the name "myEditing" and the Space key.

image

import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.JTextComponent;

/**
 * @see https://stackoverflow.com/a/38051001/230513
 */
public class TableTest {

    private void display() {
        JFrame f = new JFrame("TableTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DefaultTableModel model = new DefaultTableModel(
            new String[][]{
                {"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",}
        ) {
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                return String.class;
            }
        };
        JTable table = new JTable(model) {

            @Override
            public Dimension getPreferredScrollableViewportSize() {
                return new Dimension(320, 160);
            }
        };
        table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "myEditing");
        table.getActionMap().put("myEditing", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                table.editCellAt(table.getSelectedRow(), table.getSelectedColumn());
                Component editor = table.getEditorComponent();
                if (editor != null) {
                    editor.requestFocus();
                    if (editor instanceof JTextComponent) {
                        JTextComponent jtc = (JTextComponent) editor;
                        EventQueue.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                jtc.setCaretPosition(jtc.getDocument().getLength());
                            }
                        });
                    }
                }
            }
        });
        table.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);
        f.add(new JScrollPane(table));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new TableTest()::display);
    }
}

For reference, a similar approach for a mouse event is shown in this previous version.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
3

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.

camickr
  • 321,443
  • 19
  • 166
  • 288