How to make JTable cells overwrite by default

JTable cells are by default in add mode when the cell is double clicked. Is there a way to make the default cell instead of the rewritable mode, IOW, select the contents of the cell so that if the user started to enter old text, it would be replaced with new text without manually deleting it?

+3
source share
3 answers

You must do this by creating your own TableCellEditor , which can be assigned to the parent table using setCellEditor () . This object is a factory that is called by JTable when the user starts editing the cell to create the field used for the actual editing. You can return your own JTextField and simply not set the old value to achieve what you ask. You will also need to connect the listener to the text field to update the value in the table when the user has finished entering.

+4
source

You can find the Table Select All Editor .

+3
source

[addDeletePreviousOnEditBehavior], ! , TableCellEditor. :

JTable table=new JTable();
JTextField field=new JTextField();
addDeletePreviousOnEditBehavior(field);
table.setCellEditor(new DefaultCellEditor(field));

:

public static void addDeletePreviousOnEditBehavior(final JComponent field) {

    field.addFocusListener(new FocusListener() {

        @Override
        public void focusGained(FocusEvent fe) {
            field.putClientProperty(DELETE_ON_EDIT, true);
        }

        @Override
        public void focusLost(FocusEvent fe) {
        }
    });

    field.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent ke) {
        }

        @Override
        public void keyPressed(KeyEvent ke) {
            if ((!(ke.isActionKey()
                    || isSpecial(ke.getKeyCode())))
                    && ((Boolean) field.getClientProperty(DELETE_ON_EDIT))) {
                System.out.println("Key:" + ke.getKeyCode() + "/" + ke.getKeyChar());
                field.putClientProperty(DELETE_ON_EDIT, false);
                if (field instanceof JFormattedTextField) {
                    ((JFormattedTextField) field).setValue(null);
                }
                if (field instanceof JTextComponent) {
                    ((JTextComponent) field).setText(null);
                }

            }
        }

        @Override
        public void keyReleased(KeyEvent ke) {
           // do nothing
        }
    });
}
+2

Source: https://habr.com/ru/post/1772141/


All Articles