Search code examples
javaswingjtabletext-cursor

Text cursor is invisible when editing a JTable cell


The problem is that I have to click on the cell by mouse so that the text cursor is visible (after the cell get focused). I can still edit the cell even if the text cursor is invisible. When I try to get a cell focused through a keyboard key like Tab or Arrow then there's no chance the text cursor gets appeared while editing.

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class TableTest extends JFrame {
    
    private JTable table;
    private DefaultTableModel tableModel;
    
    public TableTest() {
        setSize(500, 500);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final String[] head = {"ID", "NAME"};
        tableModel = new DefaultTableModel(null, head);
        table = new JTable(tableModel);
        tableModel.addRow(new Object[] {"1", "Cristiano Ronaldo"});
        tableModel.addRow(new Object[] {"2", "Lionel Messi"});
        add(table);
    }
    
}

I want the text cursor to be visible while editing without having to manually click on the cell.


Solution

  • Your can override the JTable with code like:

    JTable table = new JTable(data, columnNames)
    {
    
        //  Select the text when the cell starts editing
        //  a) text will be replaced when you start typing in a cell
        //  b) text will be selected when you use F2 to start editing
        //  c) text will be selected when double clicking to start editing
    
        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();
                editor.requestFocusInWindow();
    
                if (e == null)
                {
                    //((JTextComponent)editor).selectAll();
                    editor.requestFocusInWindow();
                }
                else if (e instanceof MouseEvent)
                {
                    SwingUtilities.invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            //((JTextComponent)editor).selectAll();
                            editor.requestFocusInWindow();
                        }
                    });
                }
    
            }
    
            return result;
        }
    };