简体   繁体   English

如何通过拖动从JTable中删除列?

[英]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. 在Outlook中,如果我将列标题拖出表格,我可以删除表格列。 How can I do the same in Java with a Swing JTable? 如何使用Swing JTable在Java中执行相同的操作?

A default drag & drop operation is not possible because this feature is independent of the target position. 无法执行默认的拖放操作,因为此功能与目标位置无关。 It depends only from the drag source. 它仅取决于拖动源。

For this answer I used the SimpleTableDemo . 对于这个答案,我使用了SimpleTableDemo I simply add a MouseListener to the table. 我只是将一个MouseListener添加到表中。 Here the MouseListener: 这里是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. 但至少它有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM