提问人:Nethum 提问时间:10/22/2023 更新时间:10/22/2023 访问量:47
从 ListView 中获取值并显示在 JavaFX 的标签上
Get values from the ListView and display on a label in JavaFX
问:
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();
}
}
标签仅显示一个
答:
评论