Reputation: 13123
I would like to implement the common feature of resizing a column when my user double-clicks on the right border of the column. The thing I'm having trouble with is detecting that he has clicked there.
We have methods for determining the column and row of a mouse position, but I am not finding anything to help determine that the cursor was clicked on the border between columns. I suppose I can get the position of the cursor relative to the table origin, and then use the widths of the rows, etc., to figure out if the cursor is on one of the borders, but it seems like a lot of code for the purpose. Something in the UI runtime knows the cursor is on that border, because it changes the cursor shape when the cursor moves over the border.
I tried this:
JTableHeader tableHeader = table.getTableHeader();
tableHeader.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent mouseEvent)
{
int modifiers = mouseEvent.getModifiers();
int modifiersX = mouseEvent.getModifiersEx();
int row = table.rowAtPoint(mouseEvent.getPoint());
int col = table.columnAtPoint(mouseEvent.getPoint());
System.out.printf("m1 %x, m2 %x, row/col %d,%d%n", modifiers, modifiersX, row, col);
}
}
);
but the modifiers and extended modifiers are the same whether I click on a border or not, so those don't help with this.
So how can I ask the system whether that mouse click was on a border, without having to calculate the position of the borders each time?
Upvotes: 0
Views: 91
Reputation: 2486
If I understood you correctly, the thing you are trying to check is whether the mouse is on a JTable column header border or not?
The thing that you already mentioned is that, if the cursor is on the border, it will change its shape. I don't actually see any disadvantages using that functionality for your purposes.
So why not simply check for the current cursor on the mouseClicked()
event in the table header mouselistener?
Quick demo:
public static void main(String args[]) {
Test t = new Test();
SwingUtilities.invokeLater(() -> {
t.buildGui();
});
}
void buildGui() {
JFrame frame = new JFrame();
String[] header = { "col1", "col2" };
Object[][] data = { { "data1", "data2" } };
JTable table = new JTable(data, header);
table.getTableHeader().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (table.getTableHeader().getCursor().getType() == Cursor.E_RESIZE_CURSOR) {
if (e.getClickCount() == 2 && !e.isConsumed()) {
e.consume();
System.out.println("Double click on border!");
}
}
}
});
JScrollPane pane = new JScrollPane(table);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
mouseClicked()
on the table header the cursor is checked if it is the "resize cursor".I tested this and it seems to work without any disadvantages. Might not be the prettiest solution, but I couldn't think of a better one as of now.
Upvotes: 2