Cancel table selection when escape key pressed

335 Views Asked by At

I'm writing a Swing project in Java and I've recently stumbled upon a problem.

I have a JTable full of objects (car park full of cars) and this piece of code changes the position of 2 elements. If no car was selected, set the coordinates of the first car. On next click, if there already was a car selected, set coordinates of another car. Next, swap the elements with each other and erase the coordinates.

Now, I also have to implement a possibility to "cancel" my selection, e.g. after selecting the first car, if a key is pressed, the selection should be erased. Any ideas how could I do it?

    jt.addMouseListener(new java.awt.event.MouseAdapter() {
        int y1 = -1;
        int x1 = -1;
        public void mouseReleased(java.awt.event.MouseEvent e) {
            if(x1 == -1 && y1 == -1) {
                y1 = jt.rowAtPoint(e.getPoint());
                x1 = jt.columnAtPoint(e.getPoint());
            } 
            else {
                int y2 = jt.rowAtPoint(e.getPoint());
                int x2 = jt.columnAtPoint(e.getPoint());

                Car tmp = (Car)carpark[y1][x1];
                carpark[y1][x1] = carpark[y2][x2];
                carpark[y2][x2] = tmp;

                model.fireTableDataChanged();

                x1 = -1;
                y1 = -1;
                y2 = -1;
                x2 = -1;
            }
        }
    });
2

There are 2 best solutions below

3
Paco Abato On

You need a GUI component, like a JTextField, that can register a KeyListener and program the proper action: see the documentation.

Something like:

JTextField tf = new JTextField();
tf.addKeyListener(
    new KeyListener() {
            void keyPressed(KeyEvent e) {
                // your stuff here
            }
            // other methods must be overriden
    }
);

You can register a key listener for other components like buttons and panels as well.

0
c0der On

See How to Use Key Bindings.
Here is something to get you started:

InputMap im = table.getInputMap();
ActionMap am = table.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel");
am.put("cancel", new CancelAction());

CancelAction is defined by:

class CancelAction extends AbstractAction {

    @Override
    public void actionPerformed(ActionEvent e) {
       System.out.println("esc button pressed ");
    }
}