Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a column from a JTable with dragging?

In Outlook I can remove a table column if I drag the column header out of the table. How can I do the same in Java with a Swing JTable?

A default drag & drop operation is not possible because this feature is independent of the target position. It depends only from the drag source.

like image 230
Horcrux7 Avatar asked Dec 03 '25 22:12

Horcrux7


1 Answers

For this answer I used the SimpleTableDemo. I simply add a MouseListener to the table. Here the MouseListener:

class MyMouseListener implements MouseListener {
  public void mouseClicked(MouseEvent arg0) {}
  public void mouseEntered(MouseEvent arg0) {}
  public void mouseExited(MouseEvent arg0) {}
  public void mousePressed(MouseEvent arg0) {}
  public void mouseReleased(MouseEvent m) {
    JTableHeader tableHeader = (JTableHeader)m.getComponent();
    JTable table = tableHeader.getTable();
    if (!table.getBounds().contains(m.getPoint())) {
      table.removeColumn(table.getColumnModel().getColumn(
          tableHeader.columnAtPoint(m.getPoint())));
    }
  }
}

This is a really basic way, there are no exception handled or wathever. But at least it works.

like image 140
Jérôme Avatar answered Dec 05 '25 11:12

Jérôme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!