从 ListView 获取值并显示在 JavaFX 中的标签上

问题描述 投票:0回答:1

listView中有一个列表,并且有一个标签来显示我选择的项目。但是,当选择多个时,标签仅显示一个(最新选择)。我想要的是显示我选择的所有项目。

请帮我解决这个问题,我已经被困在这里很长时间了🥲

这是 FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="373.0" prefWidth="648.0" xmlns="http://javafx.com/javafx/20.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.trial.HelloController">
  <children>
    <ListView fx:id="listView" layoutX="142.0" layoutY="36.0" prefHeight="238.0" prefWidth="289.0" />
    <Label fx:id="selection" layoutX="36.0" layoutY="325.0" prefHeight="26.0" prefWidth="166.0" text="Your selection">
      <font>
        <Font size="17.0" />
      </font>
    </Label>
  </children>
</AnchorPane>

这是控制器

package com.example.trial;


import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;

import java.net.URL;
import java.util.ResourceBundle;

public class HelloController implements Initializable {

    @FXML
    private ListView<String> listView;

    @FXML
    private Label selection;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        String[] items = {"Java","C#","C","C++","Python"};
        listView.getItems().addAll(items);
        listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

        listView.getSelectionModel().getSelectedItems().addListener((ListChangeListener<? super String>) c -> selectionChanged());
    }

    private void selectionChanged(){
        ObservableList<String> selectedItems = listView.getSelectionModel().getSelectedItems();
        String getSelectedItem = (selectedItems.isEmpty())?"No Selected Item":selectedItems.toString();
        selection.setText(getSelectedItem);
    }
}

这是主要的

package com.example.trial;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 800, 500);
        stage.setTitle("Hello!");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

标签仅显示一个

java list javafx javafx-8
1个回答
0
投票

信息

你的代码有效,我在本地尝试过。

解决方案

在图片上,您仅选择了一项。如果要选择多个项目,请使用 CTRL + 左键单击来选择多个项目。 :)

© www.soinside.com 2019 - 2024. All rights reserved.