Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I clear text in JTable when type?

Can I make my textField in JTable acts like a cell in Excel? Clear the text when typing in but can editing when get into the cell.

I think these 2 operations will goes to the same event. Am I wrong?

I try to use the keyPressed but nothing work. TT-TT

Here is my code

private JTable getTblMaster() {
    if (tblMasterData == null) {
        tblMasterData = new JTable() {

            private static final long serialVersionUID = 1L;

            public TableCellEditor getCellEditor(int row, int column) {

                TableColumn tableColumn = getColumnModel()
                        .getColumn(column);

                TableCellEditor editor = tableColumn.getCellEditor();
                try {
                    if (editor == null) {
                            final JTextField text = new JTextField();
                            /*
                            text.addKeyListener(new java.awt.event.KeyAdapter() {
                                public void keyPressed(KeyEvent e){

                                }
                            });

                            SwingUtilities.invokeLater(new Runnable(){
                               public void run(){

                               }
                            });
                            */  
                            editor = new DefaultCellEditor(text);
                        ;
                        return editor;
                    }
                } catch (Exception e) {
                    LogWriter.error(e);
                }
                return editor;
            }
        };
    }
    return tblMasterData;
}

Any suggestion?

like image 727
swingNoobie Avatar asked Feb 20 '23 05:02

swingNoobie


2 Answers

better could be select all text in the JTable cell

text.setText(text.getText())
text.selectAll

by wrapping into invokeLater()

great workaround Table Select All Editor by @camickr

like image 76
mKorbel Avatar answered Feb 23 '23 14:02

mKorbel


Ohh! trashgod. Your example saved my life :D

All I needed was the code below and it worked. How easy! Thank you very very much.

private JTable getTblMaster() {
    if (tblMasterData == null) {
        tblMasterData = new JTable() {
           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 KeyEvent) {
                    ((JTextComponent) editor).selectAll();
                }
                return result;
            }    ....
like image 34
swingNoobie Avatar answered Feb 23 '23 14:02

swingNoobie