JavaFx:How to create a combo box in Java Fx?
For generating combo box you should have a structure as provided below in JavaFx project.
We have created this combo box to display the selected value in a label. You can modify code according to your requirement.
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
Parent root=FXMLLoader.load(getClass().getResource("/application/Main.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
MainController.java
package application;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
public class MainController implements Initializable{
@FXML
public Label mylabel;
@FXML
public ComboBox<String> combobox;
ObservableList<String> list=FXCollections.observableArrayList("first","second","third");
@Override
public void initialize(URL location, ResourceBundle resources) {
combobox.setItems(list);
}
public void combochanged(){
mylabel.setText(combobox.getValue());
}
}
Main.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="300.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainController">
<children>
<ComboBox fx:id="combobox" layoutX="50.0" layoutY="101.0" onAction="#combochanged" prefHeight="49.0" prefWidth="194.0" promptText="select Name" />
<Label fx:id="mylabel" layoutX="53.0" layoutY="178.0" prefHeight="34.0" prefWidth="187.0" text="Label" />
</children>
</AnchorPane>
Output
You will get an output display as provided below.
No comments:
Post a Comment