---
category: swing
folder: SlideTableRows
title: JTableで行の追加、削除アニメーション
tags: [JTable, Animation]
author: aterai
pubdate: 2009-04-06T14:03:11+09:00
description: JTableの行追加や削除をスライドアニメーションで強調します。
image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTTP0i2yxI/AAAAAAAAAkE/DQKpmn3BIQo/s800/SlideTableRows.png
hreflang:
href: https://java-swing-tips.blogspot.com/2009/04/animating-jtable-rows.html
lang: en
---
* Summary [#summary]
`JTable`の行追加や削除をスライドアニメーションで強調します。
#download(https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTTP0i2yxI/AAAAAAAAAkE/DQKpmn3BIQo/s800/SlideTableRows.png)
* Source Code Examples [#sourcecode]
#code(link){{
public void createActionPerformed(JTable table, DefaultTableModel model) {
model.addRow(new Object[] {"New name", model.getRowCount(), false});
int index = table.convertRowIndexToView(model.getRowCount() - 1);
AtomicInteger height = new AtomicInteger(START_HEIGHT);
new Timer(DELAY, e -> {
int h = height.getAndIncrement();
if (h < END_HEIGHT) {
table.setRowHeight(index, h);
} else {
((Timer) e.getSource()).stop();
}
}).start();
}
public void deleteActionPerformed(JTable table, DefaultTableModel model) {
int[] selection = table.getSelectedRows();
if (selection.length == 0) {
return;
}
AtomicInteger height = new AtomicInteger(END_HEIGHT);
new Timer(DELAY, e -> {
int h = height.getAndDecrement();
if (h > START_HEIGHT) {
for (int i = selection.length - 1; i >= 0; i--) {
table.setRowHeight(selection[i], h);
}
} else {
((Timer) e.getSource()).stop();
for (int i = selection.length - 1; i >= 0; i--) {
model.removeRow(table.convertRowIndexToModel(selection[i]));
}
}
}).start();
}
}}
* Description [#explanation]
* Description [#description]
上記のサンプルでは、`javax.swing.Timer`を使用して徐々に行の高さを拡大、または縮小することで、追加と削除のアニメーションを行っています。
- 行の追加アニメーション
-- 高さ`0`の行を追加したあと`JTable#setRowHeight(int, int)`メソッドを使用してその高さをデフォルトの高さになるまで拡大
- 行の削除アニメーション
-- 選択された行の高さを`JTable#setRowHeight(int, int)`メソッドを使用して縮小
-- 高さが一定以下になったらその行を削除
* Reference [#reference]
- [[JTableの行を追加、削除>Swing/AddRow]]
- [[JTableの行の高さを変更する>Swing/FishEyeTable]]
* Comment [#comment]
#comment
#comment