ChoiceBox and labels in JavaFX
Write a JavaFX application that creates a ChoiceBox with a list of colors. Display a label that changes its text based on the selected color from the ChoiceBox.
Sample Solution:
JavaFx Code:
Explanation:
In the exercise above -
- Import the necessary JavaFX libraries.
- Create a class "Main" that extends "Application" and overrides the "start()" method.
- Inside the "start()" method:
- Create a label with the initial text "Selected Color:."
- Create a ChoiceBox that contains a list of colors (Red, Green, Blue, Yellow, Orange, Purple). The "FXCollections.observableArrayList()" method is used to populate the ChoiceBox.
- Set an action for the ChoiceBox:
- When a color is selected, it updates the label's text to show the selected color.
- Organize the ChoiceBox and label in a vertical layout (VBox) with 10 pixels of spacing between them.
- Create a Scene with the layout, setting the window dimensions to 300x200.
- Set the window's title to "Color Choice App."
- Show the window.
Sample Output:
Flowchart:
Java Code Editor:
Previous:Text input and display in JavaFX.
Next: Image display in JavaFX.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.