How to do JTable on cellchange select all text

前端 未结 3 1443
囚心锁ツ
囚心锁ツ 2021-01-19 06:45

i have seen some example of doing it but i still can\'t understand and not able to implement it.

What i want to do is on cell change (focus), the next selected cell

3条回答
  •  长情又很酷
    2021-01-19 06:58

    regarding editorComponent, where do I initialize this variable?

    The variable editorComponent is a field of DefaultCellEditor.

    Instead of

    class CellEditor extends JTextField implements TableCellEditor
    

    consider

    class CellEditor extends DefaultCellEditor
    

    Then you can do something like this:

    @Override
    public Component getTableCellEditorComponent(JTable table,
            Object value, boolean isSelected, int row, int column) {
        JTextField ec = (JTextField) editorComponent;
        if (isSelected) {
            ec.selectAll();
        }
        return editorComponent;
    }
    

    Addendum: As suggested by @Edoz and illustrated in this complete example, you can selectively re-queue the selectAll() when a mouse-click initiates editing.

    JTable table = new JTable(model) {
    
        @Override // Always selectAll()
        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)) {
                return result;
            }
            if (e instanceof MouseEvent) {
                EventQueue.invokeLater(() -> {
                    ((JTextComponent) editor).selectAll();
                });
            } else {
                ((JTextComponent) editor).selectAll();
            }
            return result;
        }
    };
    

提交回复
热议问题