<AI>
JavaFXのTableViewで1行単位(特定の行のデータのみ)を書き換えるには、
対象となるデータのモデルオブジェクトを新しい値に更新するのが最も簡単で確実です。
以下に手順と具体的なコード例をまとめました。
1. 基本的なアプローチ
TableViewに設定されているObservableListから、更新したい行のインデックスを取得し、
その位置のオブジェクトを新しいデータで置き換えます。
2. 具体的なコード例
以下の例では、ボタンを押した際に選択中の行(または指定したインデックスの行)のデータを書き換えています。
java
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TableViewUpdateExample extends Application {
// データモデルクラス
public static class Person {
private final SimpleStringProperty name;
private final SimpleStringProperty status;
public Person(String name, String status) {
this.name = new SimpleStringProperty(name);
this.status = new SimpleStringProperty(status);
}
public String getName() { return name.get(); }
public void setName(String name) { this.name.set(name); }
public String getStatus() { return status.get(); }
public void setStatus(String status) { this.status.set(status); }
}
@Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
ObservableList<Person> data = FXCollections.observableArrayList(
new Person("田中", "作業中"),
new Person("佐藤", "待機中"),
new Person("鈴木", "作業中")
);
// カラム設定
TableColumn<Person, String> nameCol = new TableColumn<>("名前");
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
TableColumn<Person, String> statusCol = new TableColumn<>("ステータス");
statusCol.setCellValueFactory(new PropertyValueFactory<>("status"));
table.setItems(data);
table.getColumns().addAll(nameCol, statusCol);
// 1行書き換えボタン
Button updateButton = new Button("選択行を更新");
updateButton.setOnAction(e -> {
int selectedIndex = table.getSelectionModel().getSelectedIndex();
if (selectedIndex >= 0) {
// 新しいデータを作成して指定インデックスを上書き
Person updatedPerson = new Person("山田", "完了");
data.set(selectedIndex, updatedPerson);
}
});
VBox vbox = new VBox(table, updateButton);
Scene scene = new Scene(vbox);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
注意点・ポイント
・ data.set(index, newObject) の利用:
リストの set メソッドを使うことで、
TableView に行が変更されたことが通知され、画面の表示が自動的に更新されます。
・ JavaFXプロパティの利用:
もしデータモデル(今回の例では Person クラス)の各フィールドに StringProperty や IntegerProperty などのプロパティを使っている場合、
行全体を入れ替えるのではなく、対象プロパティの値を直接書き換えることでも1行単位の更新が可能です
(例: table.getItems().get(index).setStatus("完了"); )。