How to remove a column from JTable using drag and drop?

In Outlook, I can delete a column of a table by dragging a column heading from a table. How can I do the same in Java with Swing JTable?

The default drag and drop operation is not possible because this function is independent of the target position. It depends only on the drag source.

+3
source share
1 answer

For this answer, I used SimpleTableDemo . I just add a MouseListener to the table. Here's 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 easy way, the exception is not handled and not saved. But at least it works.

+3
source

Source: https://habr.com/ru/post/1702916/


All Articles