Hello everyone,

I have my code that is supposed to append an empty row to a table at runtime when a user presses the enter button.
The code is working fine.
here is the code if it helps:

        table.addKeyListener(new KeyListener() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) { 

                //some code should come right over here
                    dtm.addRow(new Object[]{"", ""});
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
            }

            @Override
            public void keyTyped(KeyEvent e) {
            }
        });
    }

The problem is: The row is being added when the user presses the enter button despite which cell/row/column has the focus. I mean its doing everytime the enter button is hit.

This is not what i want. I want it to do that ONLY when focus is in the LAST cell of the LAST row in the table.

I will add an image to show where i want this behaviour to happen when the enter button is hit.

How do i get this done?
I appreciate any idea on this issue. thank you in advance.

How about checking the values of getEditingColumn() and getEditingRow() ?
(Details are in the API doc as always.)

okay fine,

thanks for the idea but how do i tell that its the middle cell or the last cell?
the logic is escaping me right over here.
Should i use a loop with getEditingRow?

You need to add an if statement to check if the row you are currently editing - getEditingRow() - is greater than or equal to what TableModel's getRowCount() function returns.

Hie Le,

I have tried this:

public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    if((dtm.getRowCount())>=table.getEditingRow())
                    dtm.addRow(new Object[]{"", ""});
                }

but is not changing. please assist.

If row numbers are 0-based, you will never get a row number >= rowCount.

With a problem like that it's always quicker and easier to do a little bit of debugging. If you simply print the retuirn values of those method calls on line 3 you will immediately see what's happening.

  • JTable with KeyListener hasn't someting (never, doesn't react to) with KeyEvents in the TableCellEditorr, this is separate JComponent

  • fpr more informations about to read Oracle tutorial HOw to use Tables, part - Concepts: Editors and Renderers

  • never to use low level KeyListener for Swing JComponents, every JComponents has implementer poper listener for every of events

okay thanks, it worked.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.