How to clean JTable cell when starting typing?

1

How can I clear the cell in JTable when starting to type in a like cell in excel.

For example, I position the cursor in a cell and when I start typing the cell goes into editing mode, at this moment I need a listener that when entering the cell the content is replaced with what was typed, reminding give two clicks with the mouse the content can not clear, just when typing something.

    
asked by anonymous 19.10.2015 / 16:47

1 answer

0

Here's the solution, not so obvious but it works.

public class MyJTable extends JTable {

    boolean isSelectAll = true;


    @Override
    public boolean editCellAt(int row, int column, EventObject e) {
        boolean result = super.editCellAt(row, column, e);
        selectAll(e);
        return result;
    }

    private void selectAll(EventObject e) {
        final Component editor = getEditorComponent();
        if (editor == null
                || !(editor instanceof JTextComponent)) {
            return;
        }

        if (e == null) {
            ((JTextComponent) editor).selectAll();
            return;
        }

        //  Modo de edição ao pressionar qualquer tecla
        if (e instanceof KeyEvent && isSelectAll) {
            ((JTextComponent) editor).selectAll();
            return;
        }

        //  Modo de edição ao pressionar F2
        if (e instanceof ActionEvent && isSelectAll) {
            ((JTextComponent) editor).selectAll();
            return;
        }

        //   Modo de edição ao pressionar ao dar 2 cliques com o mouse
        if (e instanceof MouseEvent && isSelectAll) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    ((JTextComponent) editor).selectAll();
                }
            });
        }
    }

    /*
     *  habilitar/desabilitar modo de edição para selecionar tudo ao entrar na célula
     */
    public void setSelectAllForEdit(boolean isSelectAll) {
      this.isSelectAll = isSelectAll;
    }

}

SOURCE: link

    
26.10.2015 / 05:53