在Java中,沒有名為“CheckedListBox”的組件
首先,確保已經(jīng)安裝了JavaFX庫。然后,創(chuàng)建一個新的JavaFX項目并導(dǎo)入以下所需的庫:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
接下來,創(chuàng)建一個Application
類并實現(xiàn)start()
方法:
public class CheckedListBoxDemo extends Application {
@Override
public void start(Stage primaryStage) {
// 創(chuàng)建一個可觀察的列表,用于存儲數(shù)據(jù)
ObservableList<String> items = FXCollections.observableArrayList("Item 1", "Item 2", "Item 3");
// 創(chuàng)建一個ListView,用于顯示數(shù)據(jù)
ListView<String> listView = new ListView<>();
listView.setItems(items);
// 為每個列表項添加復(fù)選框
listView.setCellFactory(lv -> {
CheckBox checkBox = new CheckBox();
ListCell<String> cell = new ListCell<>();
cell.itemProperty().addListener((obs, oldValue, newValue) -> {
if (newValue != null) {
checkBox.setText(newValue);
cell.setGraphic(checkBox);
} else {
cell.setGraphic(null);
}
});
return cell;
});
// 創(chuàng)建一個VBox容器,將ListView添加到其中
VBox vbox = new VBox(listView);
vbox.setPadding(new Insets(10));
// 創(chuàng)建一個場景,將VBox容器添加到其中
Scene scene = new Scene(vbox, 300, 250);
// 設(shè)置主窗口的標(biāo)題和場景
primaryStage.setTitle("Checked List Box Demo");
primaryStage.setScene(scene);
// 顯示主窗口
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
這個例子創(chuàng)建了一個包含三個條目的ListView
,每個條目都有一個復(fù)選框。當(dāng)你運行這個程序時,你會看到一個包含復(fù)選框的列表視圖。你可以通過點擊復(fù)選框來選擇或取消選擇條目。
請注意,這個例子僅展示了如何在JavaFX中創(chuàng)建一個帶有復(fù)選框的列表視圖。要實現(xiàn)更高級的功能(例如獲取選定的條目),你需要進(jìn)一步處理復(fù)選框的狀態(tài)變化事件。