- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Basic JavaFX controls
Controls are basic building blocks of an application. A Control
is a node in the scene graph which can be manipulated by a user. It supports common user interactions in a manner which is consistent and predictable for the user. JavaFX has a wide range of built-in controls. In this chapter, we cover five controls: Label
, CheckBox
, ChoiceBox
, Slider
, and ProgressBar
. The ImageView
and TextField
controls are briefly mentioned too.
Label
Label
is a non-editable text control. A label may use an ellipsis or truncation to size the string to fit.
LabelEx.java
package com.zetcode; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.stage.Stage; /** * ZetCode JavaFX tutorial * * This program shows lyrics in a Label * control. * * Author: Jan Bodnar * Website: zetcode.com * Last modified: June 2015 */ public class LabelEx extends Application { String lyrics = "It's way too late to think of\n" + "Someone I would call now\n" + "And neon signs got tired\n" + "Red eye flights help the stars out\n" + "I'm safe in a corner\n" + "Just hours before me\n" + "\n" + "I'm waking with the roaches\n" + "The world has surrendered\n" + "I'm dating ancient ghosts\n" + "The ones I made friends with\n" + "The comfort of fireflies\n" + "Long gone before daylight\n" + "\n" + "And if I had one wishful field tonight\n" + "I'd ask for the sun to never rise\n" + "If God leant his voice for me to speak\n" + "I'd say go to bed, world\n" + "\n" + "I've always been too late\n" + "To see what's before me\n" + "And I know nothing sweeter than\n" + "Champaign from last New Years\n" + "Sweet music in my ears\n" + "And a night full of no fears\n" + "\n" + "But if I had one wishful field tonight\n" + "I'd ask for the sun to never rise\n" + "If God passed a mic to me to speak\n" + "I'd say stay in bed, world\n" + "Sleep in peace"; @Override public void start(Stage stage) { initUI(stage); } private void initUI(Stage stage) { HBox root = new HBox(); root.setPadding(new Insets(10)); Label lbl = new Label(lyrics); root.getChildren().add(lbl); Scene scene = new Scene(root); stage.setTitle("No sleep"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
The example shows lyrics of a song from Cardigans.
String lyrics = "It's way too late to think of\n" + "Someone I would call now\n" + "And neon signs got tired\n" + "Red eye flights help the stars out\n" ...
The string consists of multiple lines of text.
HBox root = new HBox(); root.setPadding(new Insets(10));
The label control is placed into a HBox
. We put some padding around the box.
Label lbl = new Label(lyrics);
A Label
control is created. It takes the string as its sole parameter.
root.getChildren().add(lbl);
The label is added to the container.
The labelFor property
The labelFor
property specifies a node to which keyboard focus is sent if a mnemonic is pressed.
LabelForEx.java
package com.zetcode; import javafx.application.Application; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.stage.Stage; /** * ZetCode JavaFX tutorial * * This program uses the labelFor property to * send focus to a specified text field. * * Author: Jan Bodnar * Website: zetcode.com * Last modified: June 2015 */ public class LabelForEx extends Application { @Override public void start(Stage stage) { initUI(stage); } private void initUI(Stage stage) { GridPane root = new GridPane(); root.setVgap(10); root.setHgap(5); root.setPadding(new Insets(10)); Label lbl1 = new Label("_Name:"); Label lbl2 = new Label("_Address:"); Label lbl3 = new Label("_Occupation:"); TextField field1 = new TextField(); TextField field2 = new TextField(); TextField field3 = new TextField(); lbl1.setLabelFor(field1); lbl1.setMnemonicParsing(true); lbl2.setLabelFor(field2); lbl2.setMnemonicParsing(true); lbl3.setLabelFor(field3); lbl3.setMnemonicParsing(true); root.add(lbl1, 0, 0); root.add(field1, 2, 0); root.add(lbl2, 0, 1); root.add(field2, 2, 1); root.add(lbl3, 0, 2); root.add(field3, 2, 2); GridPane.setHalignment(lbl1, HPos.RIGHT); GridPane.setHalignment(lbl2, HPos.RIGHT); GridPane.setHalignment(lbl3, HPos.RIGHT); Scene scene = new Scene(root); stage.setTitle("TextField"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
The example uses the labelFor
property and a mnemonic to transfer focus to the specified text field.
GridPane root = new GridPane(); root.setVgap(10); root.setHgap(5); root.setPadding(new Insets(10));
Our application is a typical form-based program. The GridPane
is well suited for this. We set some space around the controls and between them.
Label lbl1 = new Label("_Name:"); Label lbl2 = new Label("_Address:"); Label lbl3 = new Label("_Occupation:");
Three Labels
are created. The underscore character precedes the mnemonic key.
TextField field1 = new TextField(); TextField field2 = new TextField(); TextField field3 = new TextField();
TextField
is a control for editing single line of unformatted text. Each text field is placed next to one label control.
lbl1.setLabelFor(field1);
The setLabelFor()
sets a target node to which the focus is transferred when the mnemonic is pressed.
lbl1.setMnemonicParsing(true);
Mnemonics are not set for labels by default. We must enable them with the setMnemonicParsing()
method.

Under some platforms, it is neccesary to press the mouseless modifier (usually Alt) for the underlines to be shown. In the figure, the focus was transferred to the middle text field by pressing Alt+A.
CheckBox
CheckBox
is a tri-state selection control box showing a checkmark or tick mark when checked. The control has two states by default: checked and unchecked. The setAllowIndeterminate()
enables the third state: indeterminate.
CheckBoxEx.java
package com.zetcode; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.layout.HBox; import javafx.stage.Stage; /** * ZetCode JavaFX tutorial * * This program presents the * CheckBox control. * * Author: Jan Bodnar * Website: zetcode.com * Last modified: June 2015 */ public class CheckBoxEx extends Application { @Override public void start(Stage stage) { initUI(stage); } private void initUI(Stage stage) { HBox root = new HBox(); root.setPadding(new Insets(10, 0, 0, 10)); CheckBox cbox = new CheckBox("Show title"); cbox.setSelected(true); cbox.setOnAction((ActionEvent event) -> { if (cbox.isSelected()) { stage.setTitle("CheckBox"); } else { stage.setTitle(""); } }); root.getChildren().add(cbox); Scene scene = new Scene(root, 300, 200); stage.setTitle("CheckBox"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
The example shows or hides the title of the window depending whether the check box is selected.
CheckBox cbox = new CheckBox("Show title");
A CheckBox
control is created. The specified text is its label.
cbox.setSelected(true);
Since the title of the window is visible by default, we check the control with the setSelected()
method.
cbox.setOnAction((ActionEvent event) -> { if (cbox.isSelected()) { stage.setTitle("CheckBox"); } else { stage.setTitle(""); } });
With the setOnAction()
method, we set the check box's action, which is invoked when the check box is fired. We determine its state with the isSelected()
method. Depending on the current state, we show or hide the window title with the setTitle()
method.

Note the blue rectangle around the text of the check box. It indicates that this control has keyboard focus. It is possible to select and deselect the check box with the Space key.
Slider
Slider
is a control that lets the user graphically select a value by sliding a knob within a bounded interval. The slider can optionally show tick marks and labels indicating different slider position values.
SliderEx.java
package com.zetcode; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Slider; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.stage.Stage; /** * ZetCode JavaFX tutorial * * This program uses a Slider control to * manipulate the images of an ImageView. * * Author: Jan Bodnar * Website: zetcode.com * Last modified: June 2015 */ public class SliderEx extends Application { private ImageView iview; private Image muteImg; private Image minImg; private Image maxImg; private Image medImg; @Override public void start(Stage stage) { initUI(stage); } private void initUI(Stage stage) { HBox root = new HBox(10); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(15)); loadImages(); iview = new ImageView(muteImg); Slider slider = new Slider(0, 100, 0); slider.valueProperty().addListener(new MyChangeListener()); Scene scene = new Scene(root); root.getChildren().addAll(slider, iview); stage.setTitle("Slider"); stage.setScene(scene); stage.show(); } private void loadImages() { muteImg = new Image("file:mute.png"); minImg = new Image("file:min.png"); maxImg = new Image("file:max.png"); medImg = new Image("file:med.png"); } private class MyChangeListener implements ChangeListener<Number> { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { Double value = newValue.doubleValue(); if (value == 0) { iview.setImage(muteImg); } else if (value > 0 && value <= 30) { iview.setImage(minImg); } else if (value > 30 && value < 80) { iview.setImage(medImg); } else { iview.setImage(maxImg); } } } public static void main(String[] args) { launch(args); } }
In the code example, we show a Slider
and an ImageView
control. By dragging the knob of the slider, we change the image on the label control.
root.setAlignment(Pos.CENTER);
The slider and the image view are centered in the row.
iview = new ImageView(muteImg);
ImageView
displays images loaded with the Image
class.
Slider slider = new Slider(0, 100, 0);
A Slider
control is created with the specified minimum, maximum, and current values.
slider.valueProperty().addListener(new MyChangeListener());
A listener is added to the value changes of the slider.
Double value = newValue.doubleValue(); if (value == 0) { iview.setImage(muteImg); } else if (value > 0 && value <= 30) { iview.setImage(minImg); } else if (value > 30 && value < 80) { iview.setImage(medImg); } else { iview.setImage(maxImg); }
Based on the current value of the slider, we set an appropriate image to the image view.
private void loadImages() { muteImg = new Image("file:mute.png"); minImg = new Image("file:min.png"); maxImg = new Image("file:max.png"); medImg = new Image("file:med.png"); }
The loadImages()
method loads images from the disk.

ChoiceBox
ChoiceBox
is used for presenting the user with a small set of predefined choices. When the user clicks on the box, a list of choices is shown. Only one option can be selected at a time. When this list is not showing, the currently selected choice is shown. ChoiceBox
item selection is handled by a SelectionModel
.
ChoiceBoxEx.java
package com.zetcode; import javafx.application.Application; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.SingleSelectionModel; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * ZetCode JavaFX tutorial * * This program uses a ChoiceBox. The chosen * item is shown in a label. * * Author: Jan Bodnar * Website: zetcode.com * Last modified: June 2015 */ public class ChoiceBoxEx extends Application { @Override public void start(Stage stage) { initUI(stage); } private void initUI(Stage stage) { VBox root = new VBox(35); root.setPadding(new Insets(10)); Label lbl = new Label(); ChoiceBox chbox = new ChoiceBox(FXCollections.observableArrayList( "Ubuntu", "Redhat", "Arch", "Debian", "Mint")); SingleSelectionModel model = chbox.getSelectionModel(); model.selectedItemProperty().addListener((ObservableValue observable, Object oldValue, Object newValue) -> { lbl.setText(newValue.toString()); }); root.getChildren().addAll(chbox, lbl); Scene scene = new Scene(root, 300, 250); stage.setTitle("ChoiceBox"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
In our example, we have a choice box and a label. The choice box contains a list of strings denoting names of Linux distributions. The selected item from the choice box is displayed in the label.
Label lbl = new Label();
This Label
shows the currently selected item from the choice box.
ChoiceBox chbox = new ChoiceBox(FXCollections.observableArrayList( "Ubuntu", "Redhat", "Arch", "Debian", "Mint"));
A ChoiceBox
is created. It takes an observable array list as a parameter.
SingleSelectionModel model = chbox.getSelectionModel(); model.selectedItemProperty().addListener((ObservableValue observable, Object oldValue, Object newValue) -> { lbl.setText(newValue.toString()); });
To implement a listener, we need to get the selection model with the getSelectionModel()
method. The model contains the observable selectedItem
property. Inside the handler method, we get the selected value and set it to the label.

ProgressBar
ProgressBar
is a control that indicates the processing of a particular task with a completion bar.
ProgressBarEx.java
package com.zetcode; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ProgressBar; import javafx.scene.layout.HBox; import javafx.stage.Stage; import javafx.util.Duration; /** * ZetCode JavaFX tutorial * * This program presents the ProgressBar control. * * Author: Jan Bodnar * Website: zetcode.com * Last modified: June 2015 */ public class ProgressBarEx extends Application { @Override public void start(Stage stage) { initUI(stage); } private void initUI(Stage stage) { HBox root = new HBox(15); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(10)); ProgressBar pbar = new ProgressBar(0); pbar.setPrefWidth(150); KeyFrame frame1 = new KeyFrame(Duration.ZERO, new KeyValue(pbar.progressProperty(), 0)); KeyFrame frame2 = new KeyFrame(Duration.seconds(3), new KeyValue(pbar.progressProperty(), 1)); Timeline task = new Timeline(frame1, frame2); Button btn = new Button("Start"); btn.setOnAction((ActionEvent actionEvent) -> { task.playFromStart(); }); root.getChildren().addAll(pbar, btn); Scene scene = new Scene(root); stage.setTitle("ProgressBar"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
The example consists of a progress bar and a button. The button starts the progressbar that is animated for a few seconds.
ProgressBar pbar = new ProgressBar(0);
The constructor creates a new ProgressBar
with the given progress value.
KeyFrame frame1 = new KeyFrame(Duration.ZERO, new KeyValue(pbar.progressProperty(), 0)); KeyFrame frame2 = new KeyFrame(Duration.seconds(3), new KeyValue(pbar.progressProperty(), 1)); Timeline task = new Timeline(frame1, frame2);
This code creates a simple animation task. The animation consists of two frames. The animated properties are defined as KeyValues
.
Button btn = new Button("Start"); btn.setOnAction((ActionEvent actionEvent) -> { task.playFromStart(); });
When fired, the button invokes the playFromStart()
method, which plays the animation from initial position in forward direction.

In this part of the JavaFX tutorial, we have covered basic JavaFX controls.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论