Creating a JavaFX form with styled text fields
2. Style Form TextFields with CSS
Write a JavaFX program that creates a form with text fields. Apply CSS styling to modify the appearance of the text fields, such as changing the border color, background, and text color.
Sample Solution:
JavaFx Code:
Explanation:
In the exercise above,
- Setting up the UI: The start method initializes a JavaFX window (Stage) with the title "Styled Form". It creates three text fields (TextField) and three labels (Label) to represent form elements for "Name," "Email," and "Phone."
- Layout Structure: The form elements are arranged in a vertical box (VBox) layout using the VBox class. The createFormField method pairs each label with its respective text field, creating a structure of labeled input fields.
- CSS Styling: The styles.css file contains CSS styling for form fields. It specifies a class selector .form-field .text-field to target text fields nested within elements with the class .form-field. This styling includes properties like border color, background color, and text color for the text fields within the form.
- Scene and Stylesheet: The scene (Scene) is created with the VBox layout, set to a size of 300x200 pixels. The CSS file is loaded into the scene using scene.getStylesheets().add() to apply the specified styles to the text fields within the form.
- Launching the Application: The main method launches the JavaFX application by calling launch(args).
Sample Output:
Flowchart:

Go to:
PREV : Style Multiple Buttons with Inline CSS.
NEXT : Style Labels with Custom Fonts and Alignment.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.