Search code examples
javafxcombobox

ComboBox with numbers


How can i make a ComboBox with 4 numbers? For Example:

Number of players: [ComboBox here] with 4 options "1","2","3" and "4" as answers.

I know how to make it for a string like:

package sample;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;


/**
* Created by E on 15/03/2016.
*/
public class Main extends Application{
public static void main(String[] args) {
    launch(args);
}
final Label notification = new Label ();


@Override public void start(Stage stage) {
    stage.setTitle("ComboBoxSample");
    Scene scene = new Scene(new Group(), 250, 100);

    final ComboBox numbers = new ComboBox();
    numbers.getItems().addAll(
            "One",
            "Two",
            "Three",
            "Four"

    );

    GridPane grid = new GridPane();
    grid.setVgap(4);
    grid.setHgap(10);
    grid.setPadding(new Insets(5, 5, 5, 5));
    grid.add(new Label("Number of players: "), 0, 0);
    grid.add(numbers, 1, 0);
    grid.add (notification, 1, 3, 3, 1);
    Group root = (Group)scene.getRoot();
    root.getChildren().add(grid);
    stage.setScene(scene);
    stage.show();
}
}

But can i make it also using numbers?


Solution

  • You can use the generic parameter for the combobox to specify that it should use ìnt`s:

    ComboBox<Integer> numbers = new ComboBox<Integer>();
    

    Then you should be able to insert numbers.