JavaFX の ListView の要素に、チェックボックスとテキストを一緒に表示するにはそうすればよいのか調べていたところ、Java 8 から導入された CheckBoxListCell というクラスを利用すればできることが判りました。Stack Overflow のに掲載されていた例を参考にしてサンプルを作りました。
(2016-2-29) 一部問題が見つかったため、ソースコードを修正して差し替えました。
動作環境は次の通りです。
- OS: Fedora 23 (x86_64)
- Java: jdk1.8.0_74-1.8.0_74-fcs.x86_64 (Oracle)
- IDE: NetBeans IDE 8.1
リスト:Sample_CheckBoxListCell.java
package sample_checkboxlistcell;
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Sample_CheckBoxListCell extends Application {
String[] prefData = {
"北海道", "青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県",
"茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県",
"山梨県", "長野県", "新潟県", "富山県", "石川県", "福井県", "岐阜県",
"静岡県", "愛知県", "三重県", "滋賀県", "京都府", "大阪府", "兵庫県",
"奈良県", "和歌山県", "鳥取県", "島根県", "岡山県", "広島県", "山口県",
"徳島県", "香川県", "愛媛県", "高知県", "福岡県", "佐賀県", "長崎県",
"熊本県", "大分県", "宮崎県", "鹿児島県", "沖縄県"};
@Override
public void start(Stage primaryStage) {
ListView<Item> lv = new ListView<>();
for (String prefName : prefData) {
Item pref = new Item(prefName, false);
pref.onProperty().addListener((ov, old_val, new_val) -> {
System.out.println(pref.getName() + "のチェックボックスが '"
+ old_val + "' から '" + new_val + "' に変更されました。");
});
lv.getItems().add(pref);
}
lv.setCellFactory(CheckBoxListCell.forListView((Item item) -> item.onProperty()));
lv.setPrefHeight(200);
lv.setPrefWidth(150);
StackPane root = new StackPane();
root.getChildren().add(lv);
Scene scene = new Scene(root);
primaryStage.setTitle(getClass().getSimpleName());
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Item {
private final StringProperty name = new SimpleStringProperty();
private final BooleanProperty on = new SimpleBooleanProperty();
public Item(String name, boolean on) {
setName(name);
setOn(on);
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
public final BooleanProperty onProperty() {
return this.on;
}
public final boolean isOn() {
return this.onProperty().get();
}
public final void setOn(final boolean on) {
this.onProperty().set(on);
}
@Override
public String toString() {
return getName();
}
}
public static void main(String[] args) {
launch(args);
}
}
実行例を以下に示します。
宮城県のチェックボックスが 'false' から 'true' に変更されました。 秋田県のチェックボックスが 'false' から 'true' に変更されました。 山形県のチェックボックスが 'false' から 'true' に変更されました。
参考サイト



0 件のコメント:
コメントを投稿