How to clear Jtable’s cell when starting typing?

Asked

Viewed 343 times

1

How can I clear the cell in Jtable by starting to type in an equal cell in excel.

For example, I place the cursor in a cell and when starting to type the cell enters editing mode, at this precise moment of a listener that when entering the cell the content is replaced with what was typed, remembering when giving two click with the mouse the contents cannot clean, only when typing something.

  • Have you tried anything? It has some basic code?

1 answer

0


Here is the solution, not so obvious but that 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: https://tips4java.wordpress.com/2008/10/20/table-select-all-editor/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.