编辑 JTable 单元格时文本光标不可见

Text cursor is invisible when editing a JTable cell

问题是我必须用鼠标单击单元格,以便文本光标可见(在单元格获得焦点后)。即使文本光标不可见,我仍然可以编辑单元格。当我尝试通过键盘键(如 Tab 或 Arrow)使单元格聚焦时,文本光标不可能在编辑时出现。

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

我希望文本光标在编辑时可见,而无需手动单击单元格。

您可以使用如下代码覆盖 JTable:

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