Friday 22 June 2018

JavaFX: ComboBox: Event handling

By using 'setOnAction' method of ComboBox widget, you can add event handling functionality to the combo box.

Ex
hobbiesComboBox.setOnAction((ActionEvent e) -> {
         String selectedHobby = hobbiesComboBox.getValue();
         label.setText("You selected " + selectedHobby);
});

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.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class ComboBoxApp extends Application {

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

  ObservableList<String> hobbies = FXCollections.observableArrayList("Tennis", "Football", "Cricket", "CoCO",
    "Rugby", "kabaddy");
  ComboBox<String> hobbiesComboBox = new ComboBox<>(hobbies);
  hobbiesComboBox.setVisibleRowCount(3);
  hobbiesComboBox.setPromptText("Select Your Hobby");

  Label label = new Label();
  label.setFont(new Font("Arial", 30));
  label.setTextFill(Color.BLUEVIOLET);

  hobbiesComboBox.setOnAction((ActionEvent e) -> {

   String selectedHobby = hobbiesComboBox.getValue();
   label.setText("You selected " + selectedHobby);

  });

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

  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 application and select any option from the drop down, you can able to see the selected item in the window.




Previous                                                 Next                                                 Home

No comments:

Post a Comment