• title: JTableの行を追加、削除 tags: [JTable, JPopupMenu] author: aterai pubdate: 2004-05-03 description: JTableへの行追加と、選択行の削除をJPopupMenuから実行します。

概要

JTableへの行追加と、選択行の削除をJPopupMenuから実行します。

サンプルコード

private final DefaultTableModel model = new DefaultTableModel();
private final JTable table;

private void createActionPerformed(ActionEvent e) {
  int rc = model.getRowCount();
  model.addRow(new Object[] {rc, "New name", ""});
  //追加された最終行までスクロール
  table.scrollRectToVisible(table.getCellRect(rc, 0, true));
}

private void deleteActionPerformed(ActionEvent e) {
  int[] selection = table.getSelectedRows();
  for (int i = selection.length - 1; i >= 0; i--) {
    model.removeRow(table.convertRowIndexToModel(selection[i]));
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、ポップアップメニューを使って、行の追加と削除を行っています。

  • 追加
    • DefaultTableModeladdRowメソッドを使用し、オブジェクトの配列を行として追加
    • 追加された行が表示されるように、JTable#getCellRect(...)で行の領域を取得し、JTable#scrollRectToVisible(...)でスクロール
  • 削除
    • 複数行の削除に対応するために、indexの大きい方から削除する
    • 行のソートを行っている可能性があるので、JTable#convertRowIndexToModel(int)で、viewIndexmodelIndexに変換してからDefaultTableModel#removeRow(int modelIndex)を使って削除

参考リンク

コメント