Как заполнить combobox javafx
Перейти к содержимому

Как заполнить combobox javafx

  • автор:

Как заполнить combobox javafx

Класс javafx.scene.control.ComboBox позволяет создать выпадающий список. Данный класс типизируется типом элементов, которые будут храниться в списке.

Для создания выпадающего списка можно использовать один из конструкторов класса:

  • ComboBox() : создает пустой выпадающий список
  • ComboBox​(ObservableList items) : создает выпадающий список, заполненный элементами items

Из методов ComboBox следуюет выделить следующие:

  • void setValue(T item) : устанавливает выбранный по умолчанию элемент (если не вызвать данный метод, то по умолчанию никакой элемент не будет выбран)
  • T item getValue() : возвращает текущий выбранный элемент
  • void setOnAction​(EventHandler value) : устанавливает обработчик, который срабатывает при выборе элемента в списке

Создадим и используем выпадающий список:

import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.FlowPane; import javafx.scene.control.Label; import javafx.scene.control.ComboBox; import javafx.collections.ObservableList; import javafx.collections.FXCollections; import javafx.geometry.Orientation; public class Main extends Application < public static void main(String[] args) < Application.launch(args); >@Override public void start(Stage stage) throws Exception < ObservableListlangs = FXCollections.observableArrayList("Java", "JavaScript", "C#", "Python"); ComboBox langsComboBox = new ComboBox(langs); langsComboBox.setValue("Java"); // устанавливаем выбранный элемент по умолчанию Label lbl = new Label(); // получаем выбранный элемент langsComboBox.setOnAction(event -> lbl.setText(langsComboBox.getValue())); FlowPane root = new FlowPane(10, 10, langsComboBox, lbl); Scene scene = new Scene(root, 300, 250); stage.setScene(scene); stage.setTitle("ComboBox in JavaFX"); stage.show(); > >

Release: JavaFX 2.2

The picture of the author

Alla is a technical writer for Oracle. She lives in St. Petersburg, Russia, and develops tutorials and technical articles for Java and JavaFX technologies. Prior to her assignment at Oracle, she worked as a technical writer in different IT companies.

We Welcome Your Comments

If you have questions about JavaFX, please go to the forum.

Using JavaFX UI Controls

14 Combo Box

This chapter explains how to use combo boxes in your JavaFX application. It discusses editable and uneditable combo boxes, teaches you how to track changes in the editable combo boxes and handle events on them, and explains how to use cell factories to alter the default implementation of a combo box.

A combo box is a typical element of a user interface that enables users to choose one of several options. A combo box is helpful when the number of items to show exceeds some limit, because it can add scrolling to the drop down list, unlike a choice box. If the number of items does not exceed a certain limit, developers can decide whether a combo box or a choice box better suits their needs.

You can create a combo box in the JavaFX application by using the ComboBox class of the JavaFX API. Figure 14-1 shows an application with two combo boxes.

Figure 14-1 Application with Two Combo Boxes

Description of Figure 14-1 follows

Description of «Figure 14-1 Application with Two Combo Boxes»

Creating Combo Boxes

When creating a combo box, you must instantiate the ComboBox class and define the items as an observable list, just like other UI controls such as ChoiceBox , ListView , and TableView . Example 14-1 sets the items within a constructor.

Example 14-1 Creating a Combo Box with an Observable List

ObservableList options = FXCollections.observableArrayList( "Option 1", "Option 2", "Option 3" ); final ComboBox comboBox = new ComboBox(options);

Another possibility is to create a combo box by using an empty constructor and call the setItems method on it, as follows: comboBox.setItems(options);

When the combo box is added to the application scene, it appears in the user interface as shown in Figure 14-2.

Figure 14-2 Combo Box with Three Items

Description of Figure 14-2 follows

Description of «Figure 14-2 Combo Box with Three Items»

At any time, you can supplement the list of items with new values. Example 14-2 implements this task by adding three more items to the comboBox control.

Example 14-2 Adding Items to a Combo Box

comboBox.getItems().addAll( "Option 4", "Option 5", "Option 6" );

The ComboBox class provides handy properties and methods to use with combo boxes.

You can use the setValue method to specify the item selected in the combo box. When you call the setValue method on the ComboBox object, the selected item of the selectionModel property changes to this value even if the value is not in the combo box items list. If the items list then changes to include this value, the corresponding item becomes selected.

Similarly, you can obtain the value of the selected item by calling the getValue method. When a user selects an item, the selected item of the selectionModel property and the combo box value property are both updated to the new value.

You can also restrict the number of visible rows in the ComboBox drop down list when it is displayed. The following code line enables the display of three items for the comboBox control: comboBox.setVisibleRowCount(3) As the result of calling this method, the number of visible rows is limited to three, and a scroll bar appears (as shown in Figure 14-3).

Figure 14-3 Setting the Number of Visible Rows for a Combo Box

Description of Figure 14-3 follows

Description of «Figure 14-3 Setting the Number of Visible Rows for a Combo Box»

Although the ComboBox class has a generic notation and enables users to populate it with items of various types, do not use Node (or any subclass) as the type. Because the scene graph concept implies that only one Node object can be in one place of the application scene, the selected item is removed from the ComboBox list of items. When the selection changes, the previously selected item returns to the list and the new selection is removed. To prevent this situation, use the cell factory mechanism and the solution described in the API documentation. The cell factory mechanism is particularly helpful when you need to change the initial behavior or appearance of the ComboBox object.

The ComboBoxSample application is designed to illustrate how to use combo boxes in a typical email interface. Example 14-3 creates a such an interface, in which two combo boxes are used to select the email recipient and the priority of the message.

Example 14-3 Creating Combo Boxes and Adding Them to the Scene

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; public class ComboBoxSample extends Application < public static void main(String[] args) < launch(args); >final Button button = new Button ("Send"); final Label notification = new Label (); final TextField subject = new TextField(""); final TextArea text = new TextArea (""); String address = " "; @Override public void start(Stage stage) < stage.setTitle("ComboBoxSample"); Scene scene = new Scene(new Group(), 450, 250); final ComboBox emailComboBox = new ComboBox(); emailComboBox.getItems().addAll( "jacob.smith@example.com", "isabella.johnson@example.com", "ethan.williams@example.com", "emma.jones@example.com", "michael.brown@example.com" ); final ComboBox priorityComboBox = new ComboBox(); priorityComboBox.getItems().addAll( "Highest", "High", "Normal", "Low", "Lowest" ); priorityComboBox.setValue("Normal"); GridPane grid = new GridPane(); grid.setVgap(4); grid.setHgap(10); grid.setPadding(new Insets(5, 5, 5, 5)); grid.add(new Label("To: "), 0, 0); grid.add(emailComboBox, 1, 0); grid.add(new Label("Priority: "), 2, 0); grid.add(priorityComboBox, 3, 0); grid.add(new Label("Subject: "), 0, 1); grid.add(subject, 1, 1, 3, 1); grid.add(text, 0, 2, 4, 1); grid.add(button, 0, 3); grid.add (notification, 1, 3, 3, 1); Group root = (Group)scene.getRoot(); root.getChildren().add(grid); stage.setScene(scene); stage.show(); >>

Both combo boxes in Example 14-3 use the getItems and addAll methods to add items. When you compile and run this code, it produces the application window shown in Figure 14-4.

Figure 14-4 Email Recipient and Priority Combo Boxes

Description of Figure 14-4 follows

Description of «Figure 14-4 Email Recipient and Priority Combo Boxes»

Editable Combo Boxes

Typically, email client applications enable users to both select recipients from the address book and type a new address. An editable combo box perfectly fits this task. Use the setEditable(true) method of the ComboBox class to make a combo box editable. With the setPromptText method, you can specify the text to appear in the combo box editing area when no selection is performed. Examine the modified code of the application in Example 14-4. The bold lines are the additions made to Example 14-3.

Example 14-4 Processing Newly Typed Values in an Editable Combo Box

import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; 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; public class ComboBoxSample extends Application < public static void main(String[] args) < launch(args); >final Button button = new Button ("Send"); final Label notification = new Label (); final TextField subject = new TextField(""); final TextArea text = new TextArea (""); String address = " "; @Override public void start(Stage stage) < stage.setTitle("ComboBoxSample"); Scene scene = new Scene(new Group(), 450, 250); final ComboBox emailComboBox = new ComboBox(); emailComboBox.getItems().addAll( "jacob.smith@example.com", "isabella.johnson@example.com", "ethan.williams@example.com", "emma.jones@example.com", "michael.brown@example.com" ); emailComboBox.setPromptText("Email address"); emailComboBox.setEditable(true); emailComboBox.valueProperty().addListener(new ChangeListener() @Override public void changed(ObservableValue ov, String t, String t1) address = t1; > >); final ComboBox priorityComboBox = new ComboBox(); priorityComboBox.getItems().addAll( "Highest", "High", "Normal", "Low", "Lowest" ); priorityComboBox.setValue("Normal"); button.setOnAction(new EventHandler() @Override public void handle(ActionEvent e) if (emailComboBox.getValue() != null && !emailComboBox.getValue().toString().isEmpty()) notification.setText("Your message was successfully sent" + " to " + address); emailComboBox.setValue(null); if (priorityComboBox.getValue() != null && !priorityComboBox.getValue().toString().isEmpty()) priorityComboBox.setValue(null); > subject.clear(); text.clear(); > else notification.setText("You have not selected a recipient!"); > > >); GridPane grid = new GridPane(); grid.setVgap(4); grid.setHgap(10); grid.setPadding(new Insets(5, 5, 5, 5)); grid.add(new Label("To: "), 0, 0); grid.add(emailComboBox, 1, 0); grid.add(new Label("Priority: "), 2, 0); grid.add(priorityComboBox, 3, 0); grid.add(new Label("Subject: "), 0, 1); grid.add(subject, 1, 1, 3, 1); grid.add(text, 0, 2, 4, 1); grid.add(button, 0, 3); grid.add (notification, 1, 3, 3, 1); Group root = (Group)scene.getRoot(); root.getChildren().add(grid); stage.setScene(scene); stage.show(); > >

Besides the ability to edit emailComboBox , this code fragment implements event handling for this control. The newly typed or selected value is stored in the address variable. When users press the Send button, the notification containing the email address is shown.

Figure 14-5 captures the moment when a user is editing the email address of Jacob Smith and changing it to greg.smith@example.com.

Figure 14-5 Editing an Email Address

Description of Figure 14-5 follows

Description of «Figure 14-5 Editing an Email Address»

When the Send button is pressed, all the controls return to their default states. The clear methods are called on the TextField and TextArea objects, and the null value is set for the combo box selected items. Figure 14-6 shows the moment after the Send button is pressed.

Figure 14-6 User Interface After the Send Button Is Pressed

Description of Figure 14-6 follows

Description of «Figure 14-6 User Interface After the Send Button Is Pressed»

Applying Cell Factories to Combo Boxes

You can use the cell factory mechanism to alter the default behavior or appearance of a combo box. Example 14-5 creates a cell factory and applies it to the priority combo box to highlight priority types with special colors.

Example 14-5 Implementing a Cell Factory for the Priority Combo Box

import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Callback; public class ComboBoxSample extends Application < public static void main(String[] args) < launch(args); >final Button button = new Button ("Send"); final Label notification = new Label (); final TextField subject = new TextField(""); final TextArea text = new TextArea (""); String address = " "; @Override public void start(Stage stage) < stage.setTitle("ComboBoxSample"); Scene scene = new Scene(new Group(), 450, 250); final ComboBox emailComboBox = new ComboBox(); emailComboBox.getItems().addAll( "jacob.smith@example.com", "isabella.johnson@example.com", "ethan.williams@example.com", "emma.jones@example.com", "michael.brown@example.com" ); emailComboBox.setPromptText("Email address"); emailComboBox.setEditable(true); emailComboBox.valueProperty().addListener(new ChangeListener() < @Override public void changed(ObservableValue ov, String t, String t1) < address = t1; >>); final ComboBox priorityComboBox = new ComboBox(); priorityComboBox.getItems().addAll( "Highest", "High", "Normal", "Low", "Lowest" ); priorityComboBox.setValue("Normal"); priorityComboBox.setCellFactory( new Callback() @Override public ListCell call(ListView param) final ListCell cell = new ListCell()  super.setPrefWidth(100); > @Override public void updateItem(String item, boolean empty) super.updateItem(item, empty); if (item != null) setText(item); if (item.contains("High")) setTextFill(Color.RED); > else if (item.contains("Low")) setTextFill(Color.GREEN); > else setTextFill(Color.BLACK); > > else  setText(null); > > >; return cell; > >); button.setOnAction(new EventHandler() < @Override public void handle(ActionEvent e) < if (emailComboBox.getValue() != null && !emailComboBox.getValue().toString().isEmpty())< notification.setText("Your message was successfully sent" + " to " + address); emailComboBox.setValue(null); if (priorityComboBox.getValue() != null && !priorityComboBox.getValue().toString().isEmpty())< priorityComboBox.setValue(null); >subject.clear(); text.clear(); > else < notification.setText("You have not selected a recipient!"); >> >); GridPane grid = new GridPane(); grid.setVgap(4); grid.setHgap(10); grid.setPadding(new Insets(5, 5, 5, 5)); grid.add(new Label("To: "), 0, 0); grid.add(emailComboBox, 1, 0); grid.add(new Label("Priority: "), 2, 0); grid.add(priorityComboBox, 3, 0); grid.add(new Label("Subject: "), 0, 1); grid.add(subject, 1, 1, 3, 1); grid.add(text, 0, 2, 4, 1); grid.add(button, 0, 3); grid.add (notification, 1, 3, 3, 1); Group root = (Group)scene.getRoot(); root.getChildren().add(grid); stage.setScene(scene); stage.show(); > >

The cell factory produces ListCell objects. Every cell is associated with a single combo box item. The width of each combo box item is set through the setPrefWidth method. The updateItem method sets the red color for the High and Highest items, green color for the Low and Lowest items, and leaves the Normal item black.

Figure 14-7 shows the items of the priority combo box after the cell factory in Example 14-5 is applied.

Figure 14-7 Modified the Priority Combo Box

Description of Figure 14-7 follows

Description of «Figure 14-7 Modified the Priority Combo Box»

You can further enhance the appearance of the ComboBox control by applying CSS styles or visual effects.

Related API Documentation

16 Combo Box

This chapter explains how to use combo boxes in your JavaFX application. It discusses editable and uneditable combo boxes, teaches you how to track changes in the editable combo boxes and handle events on them, and explains how to use cell factories to alter the default implementation of a combo box.

A combo box is a typical element of a user interface that enables users to choose one of several options. A combo box is helpful when the number of items to show exceeds some limit, because it can add scrolling to the drop down list, unlike a choice box. If the number of items does not exceed a certain limit, developers can decide whether a combo box or a choice box better suits their needs.

You can create a combo box in the JavaFX application by using the ComboBox class of the JavaFX API. Figure 16-1 shows an application with two combo boxes.

Figure 16-1 Application with Two Combo Boxes

Description of Figure 16-1 follows

Description of «Figure 16-1 Application with Two Combo Boxes»

Creating Combo Boxes

When creating a combo box, you must instantiate the ComboBox class and define the items as an observable list, just like other UI controls such as ChoiceBox , ListView , and TableView . Example 16-1 sets the items within a constructor.

Example 16-1 Creating a Combo Box with an Observable List

ObservableList options = FXCollections.observableArrayList( "Option 1", "Option 2", "Option 3" ); final ComboBox comboBox = new ComboBox(options);

Another possibility is to create a combo box by using an empty constructor and call the setItems method on it, as follows: comboBox.setItems(options);

When the combo box is added to the application scene, it appears in the user interface as shown in Figure 16-2.

Figure 16-2 Combo Box with Three Items

Description of «Figure 16-2 Combo Box with Three Items»

At any time, you can supplement the list of items with new values. Example 16-2 implements this task by adding three more items to the comboBox control.

Example 16-2 Adding Items to a Combo Box

comboBox.getItems().addAll( "Option 4", "Option 5", "Option 6" );

The ComboBox class provides handy properties and methods to use with combo boxes.

You can use the setValue method to specify the item selected in the combo box. When you call the setValue method on the ComboBox object, the selected item of the selectionModel property changes to this value even if the value is not in the combo box items list. If the items list then changes to include this value, the corresponding item becomes selected.

Similarly, you can obtain the value of the selected item by calling the getValue method. When a user selects an item, the selected item of the selectionModel property and the combo box value property are both updated to the new value.

You can also restrict the number of visible rows in the ComboBox drop down list when it is displayed. The following code line enables the display of three items for the comboBox control: comboBox.setVisibleRowCount(3) As the result of calling this method, the number of visible rows is limited to three, and a scroll bar appears (as shown in Figure 16-3).

Figure 16-3 Setting the Number of Visible Rows for a Combo Box

Description of «Figure 16-3 Setting the Number of Visible Rows for a Combo Box»

Although the ComboBox class has a generic notation and enables users to populate it with items of various types, do not use Node (or any subclass) as the type. Because the scene graph concept implies that only one Node object can be in one place of the application scene, the selected item is removed from the ComboBox list of items. When the selection changes, the previously selected item returns to the list and the new selection is removed. To prevent this situation, use the cell factory mechanism and the solution described in the API documentation. The cell factory mechanism is particularly helpful when you need to change the initial behavior or appearance of the ComboBox object.

The ComboBoxSample application is designed to illustrate how to use combo boxes in a typical email interface. Example 16-3 creates a such an interface, in which two combo boxes are used to select the email recipient and the priority of the message.

Example 16-3 Creating Combo Boxes and Adding Them to the Scene

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; public class ComboBoxSample extends Application < public static void main(String[] args) < launch(args); >final Button button = new Button ("Send"); final Label notification = new Label (); final TextField subject = new TextField(""); final TextArea text = new TextArea (""); String address = " "; @Override public void start(Stage stage) < stage.setTitle("ComboBoxSample"); Scene scene = new Scene(new Group(), 500, 270); final ComboBox emailComboBox = new ComboBox(); emailComboBox.getItems().addAll( "jacob.smith@example.com", "isabella.johnson@example.com", "ethan.williams@example.com", "emma.jones@example.com", "michael.brown@example.com" ); final ComboBox priorityComboBox = new ComboBox(); priorityComboBox.getItems().addAll( "Highest", "High", "Normal", "Low", "Lowest" ); priorityComboBox.setValue("Normal"); GridPane grid = new GridPane(); grid.setVgap(4); grid.setHgap(10); grid.setPadding(new Insets(5, 5, 5, 5)); grid.add(new Label("To: "), 0, 0); grid.add(emailComboBox, 1, 0); grid.add(new Label("Priority: "), 2, 0); grid.add(priorityComboBox, 3, 0); grid.add(new Label("Subject: "), 0, 1); grid.add(subject, 1, 1, 3, 1); grid.add(text, 0, 2, 4, 1); grid.add(button, 0, 3); grid.add (notification, 1, 3, 3, 1); Group root = (Group)scene.getRoot(); root.getChildren().add(grid); stage.setScene(scene); stage.show(); >>

Both combo boxes in Example 16-3 use the getItems and addAll methods to add items. When you compile and run this code, it produces the application window shown in Figure 16-4.

Figure 16-4 Email Recipient and Priority Combo Boxes

Description of Figure 16-4 follows

Description of «Figure 16-4 Email Recipient and Priority Combo Boxes»

Editable Combo Boxes

Typically, email client applications enable users to both select recipients from the address book and type a new address. An editable combo box perfectly fits this task. Use the setEditable(true) method of the ComboBox class to make a combo box editable. With the setPromptText method, you can specify the text to appear in the combo box editing area when no selection is performed. Examine the modified code of the application in Example 16-4. The bold lines are the additions made to Example 16-3.

Example 16-4 Processing Newly Typed Values in an Editable Combo Box

import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.Event; 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; public class ComboBoxSample extends Application < public static void main(String[] args) < launch(args); >final Button button = new Button ("Send"); final Label notification = new Label (); final TextField subject = new TextField(""); final TextArea text = new TextArea (""); String address = " "; @Override public void start(Stage stage) < stage.setTitle("ComboBoxSample"); Scene scene = new Scene(new Group(), 500, 270); final ComboBox emailComboBox = new ComboBox(); emailComboBox.getItems().addAll( "jacob.smith@example.com", "isabella.johnson@example.com", "ethan.williams@example.com", "emma.jones@example.com", "michael.brown@example.com" ); emailComboBox.setPromptText("Email address"); emailComboBox.setEditable(true); emailComboBox.setOnAction((Event ev) -> address = emailComboBox.getSelectionModel().getSelectedItem().toString(); >); final ComboBox priorityComboBox = new ComboBox(); priorityComboBox.getItems().addAll( "Highest", "High", "Normal", "Low", "Lowest" ); priorityComboBox.setValue("Normal"); button.setOnAction((ActionEvent e) -> if (emailComboBox.getValue() != null && !emailComboBox.getValue().toString().isEmpty()) notification.setText("Your message was successfully sent" + " to " + address); emailComboBox.setValue(null); if (priorityComboBox.getValue() != null && !priorityComboBox.getValue().toString().isEmpty()) priorityComboBox.setValue(null); > subject.clear(); text.clear(); > else notification.setText("You have not selected a recipient!"); > >); GridPane grid = new GridPane(); grid.setVgap(4); grid.setHgap(10); grid.setPadding(new Insets(5, 5, 5, 5)); grid.add(new Label("To: "), 0, 0); grid.add(emailComboBox, 1, 0); grid.add(new Label("Priority: "), 2, 0); grid.add(priorityComboBox, 3, 0); grid.add(new Label("Subject: "), 0, 1); grid.add(subject, 1, 1, 3, 1); grid.add(text, 0, 2, 4, 1); grid.add(button, 0, 3); grid.add (notification, 1, 3, 3, 1); Group root = (Group)scene.getRoot(); root.getChildren().add(grid); stage.setScene(scene); stage.show(); > >

Besides the ability to edit emailComboBox , this code fragment implements event handling for this control. The newly typed or selected value is stored in the address variable. When users press the Send button, the notification containing the email address is shown.

Figure 16-5 captures the moment when a user is editing the email address of Jacob Smith and changing it to greg.smith@example.com.

Figure 16-5 Editing an Email Address

Description of Figure 16-5 follows

Description of «Figure 16-5 Editing an Email Address»

When the Send button is pressed, all the controls return to their default states. The clear methods are called on the TextField and TextArea objects, and the null value is set for the combo box selected items. Figure 16-6 shows the moment after the Send button is pressed.

Figure 16-6 User Interface After the Send Button Is Pressed

Description of Figure 16-6 follows

Description of «Figure 16-6 User Interface After the Send Button Is Pressed»

Applying Cell Factories to Combo Boxes

You can use the cell factory mechanism to alter the default behavior or appearance of a combo box. Example 16-5 creates a cell factory and applies it to the priority combo box to highlight priority types with special colors.

Example 16-5 Implementing a Cell Factory for the Priority Combo Box

import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Callback; public class ComboBoxSample extends Application < public static void main(String[] args) < launch(args); >final Button button = new Button ("Send"); final Label notification = new Label (); final TextField subject = new TextField(""); final TextArea text = new TextArea (""); String address = " "; @Override public void start(Stage stage) < stage.setTitle("ComboBoxSample"); Scene scene = new Scene(new Group(), 500, 270); final ComboBox emailComboBox = new ComboBox(); emailComboBox.getItems().addAll( "jacob.smith@example.com", "isabella.johnson@example.com", "ethan.williams@example.com", "emma.jones@example.com", "michael.brown@example.com" ); emailComboBox.setPromptText("Email address"); emailComboBox.setEditable(true); emailComboBox.setOnAction((Event ev) ->< address = emailComboBox.getSelectionModel().getSelectedItem().toString(); >); final ComboBox priorityComboBox = new ComboBox(); priorityComboBox.getItems().addAll( "Highest", "High", "Normal", "Low", "Lowest" ); priorityComboBox.setValue("Normal"); priorityComboBox.setCellFactory( new Callback, ListCell>() @Override public ListCell call(ListView param) final ListCell cell = new ListCell()  super.setPrefWidth(100); > @Override public void updateItem(String item, boolean empty) super.updateItem(item, empty); if (item != null) setText(item); if (item.contains("High")) setTextFill(Color.RED); > else if (item.contains("Low")) setTextFill(Color.GREEN); > else setTextFill(Color.BLACK); > > else  setText(null); > > >; return cell; > >); button.setOnAction((ActionEvent e) -> < if (emailComboBox.getValue() != null && !emailComboBox.getValue().toString().isEmpty())< notification.setText("Your message was successfully sent" + " to " + address); emailComboBox.setValue(null); if (priorityComboBox.getValue() != null && !priorityComboBox.getValue().toString().isEmpty())< priorityComboBox.setValue(null); >subject.clear(); text.clear(); > else < notification.setText("You have not selected a recipient!"); >>) GridPane grid = new GridPane(); grid.setVgap(4); grid.setHgap(10); grid.setPadding(new Insets(5, 5, 5, 5)); grid.add(new Label("To: "), 0, 0); grid.add(emailComboBox, 1, 0); grid.add(new Label("Priority: "), 2, 0); grid.add(priorityComboBox, 3, 0); grid.add(new Label("Subject: "), 0, 1); grid.add(subject, 1, 1, 3, 1); grid.add(text, 0, 2, 4, 1); grid.add(button, 0, 3); grid.add (notification, 1, 3, 3, 1); Group root = (Group)scene.getRoot(); root.getChildren().add(grid); stage.setScene(scene); stage.show(); > >

The cell factory produces ListCell objects. Every cell is associated with a single combo box item. The width of each combo box item is set through the setPrefWidth method. The updateItem method sets the red color for the High and Highest items, green color for the Low and Lowest items, and leaves the Normal item black.

Figure 16-7 shows the items of the priority combo box after the cell factory in Example 16-5 is applied.

Figure 16-7 Modified the Priority Combo Box

Description of Figure 16-7 follows

Description of «Figure 16-7 Modified the Priority Combo Box»

You can further enhance the appearance of the ComboBox control by applying CSS styles or visual effects.

Related API Documentation

Close Window

Table of Contents

JavaFX: Working with JavaFX UI Components

  • Title and Copyright Information
  • Preface
    • Audience
    • Documentation Accessibility
    • Related Documents
    • Conventions
    • 1 What Is New
    • 2 Label
      • Creating a Label
      • Setting a Font
      • Wrapping Text
      • Applying Effects
      • Creating a Button
      • Assigning an Action
      • Applying Effects
      • Styling a Button
      • Creating a Radio Button
      • Adding Radio Buttons to Groups
      • Processing Events for Radio Buttons
      • Requesting Focus for a Radio Button
      • Creating a Toggle Button
      • Adding Toggle Buttons to a Group
      • Setting the Behavior
      • Styling Toggle Buttons
      • Creating Checkboxes
      • Defining a State
      • Setting the Behavior
      • Creating a Choice Box
      • Setting the Behavior for a Choice Box
      • Applying a Tooltip
      • Creating a Text Field
      • Building the UI with Text Fields
      • Processing Text Field Data
      • Creating a Password Field
      • Evaluating the Password
      • Creating a Scroll Bar
      • Using a Scroll Bar in Your Application
      • Creating a Scroll Pane
      • Setting the Scroll Bar Policy for a Scroll Pane
      • Resizing Components in the Scroll Pane
      • Sample Application with a Scroll Pane
      • Creating a List View
      • Populating a List View with Data
      • Customizing the Content of a List View
      • Processing the List Item Selection
      • Creating a Table
      • Defining the Data Model
      • Adding New Rows
      • Sorting Data in Columns
      • Editing Data in the Table
      • Adding Maps of Data to the Table
      • Creating Tree Views
      • Implementing Cell Factories
      • Adding New Tree Items on Demand
      • Using Tree Cell Editors
      • Creating a TreeTableView control
      • Adding Several Columns
      • Altering Visual Appearance
      • Managing Selection Mode
      • Creating Combo Boxes
      • Editable Combo Boxes
      • Applying Cell Factories to Combo Boxes
      • Creating a Separator
      • Adding Separators to the UI of Your Application
      • Styling Separators
      • Creating a Slider
      • Using Sliders in Graphical Applications
      • Creating Progress Controls
      • Indicating Progress in Your User Interface
      • Creating a Hyperlink
      • Linking the Local Content
      • Linking the Remote Content
      • Adding an HTML Editor
      • Using an HTML Editor to Build the User Interface
      • Obtaining HTML Content
      • Creating a Tooltip
      • Presenting Application Data in Tooltips
      • Creating Titled Panes
      • Adding Titled Panes to an Accordion
      • Processing Events for an Accordion with Titled Panes
      • Building Menus in JavaFX Applications
      • Creating a Menu Bar
      • Adding Menu Items
      • Creating Submenus
      • Adding Context Menus
      • Design Overview
        • Color Chooser
        • Color Palette
        • Custom Color Dialog Window
        • Working with Time Data and Date Formats
        • Date Picker Design Overview
        • Adding a Date Picker to an Application UI
        • Customizing the Date Picker
        • Altering the Calendar System
        • Creating a Pagination Control
        • Implementing Page Factories
        • Styling a Pagination Control
        • Opening Files
        • Configuring a File Chooser
        • Setting Extension Filters
        • Saving Files
        • Applying CSS
        • Altering Default Behavior
        • Implementing Cell Factories
        • Embedded Runtime Features
          • Support for Touch-Enabled Devices
          • Virtual Keyboard
          • Scrolling Controls
          • Text Input Controls
          • Context Menus
          • 31 Pie Chart
            • Creating a Pie Chart
            • Setting a Pie Chart and a Legend
            • Processing Events for a Pie Chart
            • Chart Settings
            • Chart Data
            • Creating a Line Chart
            • Creating Categories for a Line Chart
            • Adding Series to the Line Chart
            • Creating an Area Chart
            • Creating a Stacked Area Chart
            • Setting Axis and Tick Properties
            • Adding Negative Values
            • Styling Area Charts
            • Creating a Bubble Chart
            • Using the Extra Value Property
            • Changing the Appearance Visual Setting of the Plot and Tick Marks
            • Creating a Scatter Chart
            • Managing Chart Data
            • Adding Effects to Charts
            • Changing the Chart Symbol
            • Creating a Bar Chart
            • Horizontal Bar Chart
            • Creating a Stacked Bar Chart
            • Animating Data in Charts
            • 37 Styling UI Controls with CSS
              • Default Style Sheet
              • Creating Style Sheets
              • Defining Styles
                • Selectors
                • Rules and Properties
                • Overriding Default Styles
                • Creating Class Styles
                • Creating ID Styles
                • Setting Styles in the Code
                • Modifying Basic Chart Elements
                • Altering Colors of the Chart Plot
                • Setting the Axes
                • Setting Chart Colors
                • Changing Chart Symbols
                • 39 Using Text in JavaFX
                  • Introduction
                  • Adding Text
                    • Setting Text Font and Color
                    • Making Text Bold or Italic
                    • Using Custom Fonts
                    • Setting LCD Text Support
                    • Rich Text and Bidirectional Support
                    • Perspective Effect
                    • Blur Effect
                    • Drop Shadow Effect
                    • Inner Shadow Effect
                    • Reflection
                    • Combining Several Effects
                    • Application Files
                    • A UI Control Samples
                      • LabelSample.java
                      • ButtonSample.java
                      • RadioButtonSample.java
                      • ToggleButtonSample.java
                      • CheckboxSample.java
                      • ChoiceBoxSample.java
                      • TextFieldSample.java
                      • PasswordField.java
                      • ScrollBarSample.java
                      • ScrollPaneSample.java
                      • ListViewSample.java
                      • TableViewSample.java
                      • TreeViewSample.java
                      • TreeTableViewSample.java
                      • ComboBoxSample.java
                      • SeparatorSample.java
                      • SliderSample.java
                      • ProgressSample.java
                      • HyperlinkSample.java
                      • HyperlinkWebViewSample.java
                      • HTMLEditorSample.java
                      • TooltipSample.java
                      • TitledPaneSample.java
                      • MenuSample.java
                      • ColorPickerSample.java
                      • DatePickerSample.java
                      • PaginationSample.java
                      • FileChooserSample.java
                      • PieChartSample.java
                      • LineChartSample.java
                      • AreaChartSample.java
                      • BubbleChartSample.java
                      • ScatterChartSample.java
                      • BarChartSample.java
                      • DownloadButton.java
                      • DownloadButtonStyle1.css
                      • DownloadButtonStyle2.css
                      • StyleStage.java
                      • UIControlCSS.java
                      • controlStyle1.css
                      • controlStyle2.css
                      • TextEffects.java
                      • NeonSign.java

                      How do I add a value to items in a ComboBox in JavaFX

                      How can I add a value to items in a combo box so when the user selects an item from the ComboBox I am able to display the price for that item Eg. if the user selects an animal I can display the price of that animal. The the user selects dog then I can display the price of $45 .

                      public class comboBox extends Application < Stage window; Scene scene; Button button; ComboBoxcomboBox; public static void main(String[] args) < launch(args); >@Override public void start(Stage primaryStage) throws Exception < window = primaryStage; window.setTitle("ComboBox"); button = new Button("Submit"); comboBox = new ComboBox<>(); comboBox.getItems().addAll( "cat", "dog", "bird" ); comboBox.setPromptText("Please select one"); button.setOnAction(e -> printPrice()); VBox layout = new VBox(10); layout.setPadding(new Insets(60, 60, 60, 60)); layout.getChildren().addAll(comboBox, button); scene = new Scene(layout, 450, 350); window.setScene(scene); window.show(); > private void printPrice() < System.out.println(comboBox.getValue()); >> 

                      I have tried to fix the code and this is what I got there is still a few errors anyone know what I am doing wrong?

                      import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.collections.FXCollections; public class animals extends Application < Stage window; Scene scene; Button button; ComboBoxcomboBox; public static void main(String[] args) < launch(args); >@Override public void start(Stage primaryStage) throws Exception < window = primaryStage; window.setTitle("ComboBox "); button = new Button("Submit"); comboBox.setConverter(new StringConverter() < @Override public String toString(Animal object) < return object.getName(); >@Override public Animal fromString(String string) < return null; >>); ComboBox comboBox = new ComboBox(); comboBox.setItems(FXCollections.observableArrayList(new Animal("Dog", 30.12), new Animal("Cat", 23.23), new Animal("Bird", 15.0))); comboBox.valueProperty().addListener((obs, oldVal, newVal) -> System.out.println("Price of the " + newVal.getName() + " is : " + newVal.getPrice())); > VBox layout = new VBox(10); layout.setPadding(new Insets(60, 60, 60, 60)); layout.getChildren().addAll(comboBox, button); scene = new Scene(layout, 500, 350); window.setScene(scene); window.show(); > public class Animal < private String name; private Double price; public Double getPrice() < return price; >public String getName() < return name; >public Animal(String name, Double price) < this.name = name; this.price = price; >> 

                      also, how would I be able to display the price under the combo box after the user selects an animal? so it would say ‘the price for that animal cost’

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *