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;
}
}
});