Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaFx: ComboBox: Add items to the combo box dynamically

You can Add Items to the Combo Box at any point of time.

Ex
hobbiesComboBox.getItems().add("CoCo");
hobbiesComboBox.getItems().addAll("Rugby", "kabaddy");

Find the below working application.

ComboBoxApp.java
package com.sample.demos;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ComboBoxApp extends Application {
private static boolean isAdded = false;

@Override
public void start(Stage primaryStage) throws Exception {

ObservableListString> hobbies = FXCollections.observableArrayList("Tennis", "Football", "Cricket");
ComboBoxString> hobbiesComboBox = new ComboBox(hobbies);

Button button = new Button("Add Some more hobbies");
button.setOnAction(new EventHandlerActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (!isAdded) {
hobbiesComboBox.getItems().add("CoCo");
hobbiesComboBox.getItems().addAll("Rugby", "kabaddy");
isAdded = true;
}
}
});

HBox hBox = new HBox(10, hobbiesComboBox, button);

primaryStage.setScene(new Scene(hBox));
primaryStage.setTitle("Combo Box Example");
primaryStage.setWidth(900);
primaryStage.setHeight(500);
primaryStage.show();
}

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
public static void main(String args[]) {
Application.launch(ComboBoxApp.class, args);
}
}

Run the above application and click on the combo box, you can able to see below kind of window.


After click on the button ‘Add Some more hobbies’, you can able to see 3 more hobbies added to the combo box.




Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

JavaFx: ComboBox: Add items to the combo box dynamically

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×