JavaFX - ListView



ListView 是一種圖形使用者介面元件,用於顯示專案列表,使用者可以從中選擇所需的專案。通常,列表指的是一組或一系列專案。它有助於以更使用者友好和易讀的方式組織、構建和呈現資訊。下圖顯示了一個城市列表檢視,使用者可以從中選擇一個選項 -

JavaFX ListView

JavaFX 中的 ListView

在 JavaFX 中,列表檢視由名為 ListView 的類表示,它是 javafx.scene.control 包的一部分。我們可以透過例項化此類來建立列表檢視元件。此外,我們還可以選擇其方向,使其垂直或水平顯示。ListView 類的建構函式列表如下 -

  • ListView() - 這是預設建構函式,用於構造一個垂直列表檢視。

  • ListView(ObservableList<type> listItems) - 它使用指定的列表項構造一個新的垂直列表檢視。

在 JavaFX 中建立 ListView

要在任何 JavaFX 應用程式中建立 ListView,我們可以使用 ListView 類的預設建構函式或引數化建構函式。如果使用預設建構函式,則應顯式傳遞列表項。引數化建構函式接受 ArrayList 物件作為引數值,如下面的程式碼塊所示 -

//list View for educational qualification
ObservableList<String> names = FXCollections.observableArrayList("Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> listView = new ListView<String>(names);

一旦 ListView 類被例項化並添加了其專案,請定義任何佈局窗格(如 VBox 或 HBox)來容納列表檢視。接下來,透過將佈局窗格物件和 Scene 的尺寸傳遞給其建構函式來建立一個 Scene 物件。然後,設定舞臺並啟動應用程式以顯示結果。

示例

在以下示例中,我們將演示如何在 JavaFX 中建立 ListView。將此程式碼儲存在名為 JavafxListview.java 的檔案中。

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class JavafxListview extends Application {
   public void start(Stage stage) {
      //Label for education
      Label label = new Label("Educational qualification:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //list View for educational qualification
      ObservableList<String> names = FXCollections.observableArrayList("Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
      ListView<String> listView = new ListView<String>(names);
      listView.setMaxSize(200, 160);
      //Creating the layout
      VBox layout = new VBox(10);
      layout.setPadding(new Insets(5, 5, 5, 50));
      layout.getChildren().addAll(label, listView);
      layout.setStyle("-fx-background-color: BEIGE");
      //Setting the stage
      Scene scene = new Scene(layout, 400, 300);
      stage.setTitle("List View Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

使用以下命令從命令提示符編譯並執行儲存的 Java 檔案 -

javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxListview.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxListview

輸出

執行上述程式碼後,它將生成一個視窗,顯示一個 ListView,如下面的輸出所示 -

Listview Output
廣告