Note: This does not directly answer the posted question, but is meant to provide another means of accomplishing the OP's apparent overall goal.
While you could certainly suppress the warning as another answer suggests, I wonder if you might be better off implementing a Listener
on your ComboBox
instead.
You can easily add a Listener
that will execute code whenever a new value is selected from the ComboBox
:
comboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
label.setText(newValue);
}
});
This has a couple of benefits over your current implementation:
- You do not need to worry about casting or checking the event source.
- Your current implementation would throw a
NulLPointerException
if no value is selected. The if (newValue != null)
checks for that.
- You do not need to write a separate method to handle selection changes.
Here is a quick sample application to demonstrate:
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();
}
}