我用JavaFX / Scenebuilder构建了一个GUI,它有多个具有类似功能的下拉列表。我想对所有下拉列表使用相同的函数,所以我必须检查动作事件的来源。我目前的代码是:public void dropdownPressed(ActionEvent event) { ComboBox<String> comboBox = (ComboBox<String>) event.getSource(); Label.setText(comboBox.getSelectionModel().getSelectedItem());}它有效,但它发出以下警告:Type safety: Unchecked cast from Object to ComboBox<String>所以根据我的理解,getSource()返回一个通用的Object,不能保证可以转换为ComboBox?这个问题的解决方案是什么?
1 回答

慕容3067478
TA贡献1773条经验 获得超3个赞
虽然你当然可以抑制警告作为另一个答案表明,我不知道你可能会更好实现Listener
你的ComboBox
来代替。
Listener
每当从以下位置选择新值时,您都可以轻松添加将执行代码的代码ComboBox
:
comboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (newValue != null) { label.setText(newValue); }});
这比您当前的实现有几个好处:
您无需担心转换或检查事件源。
NulLPointerException
如果没有选择任何值,您当前的实现将抛出。在if (newValue != null)
该检查。您不需要编写单独的方法来处理选择更改。
这是一个快速示例应用程序来演示:
import javafx.application.Application;import javafx.geometry.Insets;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx. scene.control.ComboBox;import javafx.scene.control.Label;import javafx.scene.layout.VBox;import javafx.stage.Stage; public class DropDownListener extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { // Simple interface VBox root = new VBox(5); root.setPadding(new Insets(10)); root.setAlignment(Pos.CENTER); // Simple ComboBox ComboBox<String> comboBox = new ComboBox<>(); comboBox.getItems().addAll("One", "Two", "Three", "Four", "Five"); // Label to show selection Label label = new Label(); // Use a listener to update the Label when a new item is selected from the ComboBox comboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> { if (newValue != null) { label.setText(newValue); } }); root.getChildren().addAll(comboBox, label); // Show the Stage primaryStage.setWidth(300); primaryStage.setHeight(300); primaryStage.setScene(new Scene(root)); primaryStage.show(); }}
添加回答
举报
0/150
提交
取消