cs3391 Oop Unitvnotesfinal 230308123741 8c49417b
cs3391 Oop Unitvnotesfinal 230308123741 8c49417b
CLASS NOTES
Complimented with
PERSONALIZED LEARNING
MATERIAL (PLM)
With
PERSONALIZED ASSESSMENT
TESTS (PATs)
ction to PERSONALIZED LEARNING MATERIAL (PLM)
The PERSONALIZED LEARNING MATERIAL (PLM) is special Type of
Learning Material designed and developed by Er. K.Khaja Mohideen , Assistant
Professor , Aalim Muhammed Salegh College of Engineering, Avadi-IAF,
Chennai – 600 055, India.
This material called PLM is an innovative Learning Type based Artificial
Intelligence based Suggestive learning Strategy (SLS) that recommends the
selective Topics to Learners of different Learning mind sets groups.
We identified three major such Learner Groups from Subject Learning
Student Communities and are as follows:
1) Smart Learning Groups
2) Effective Learning Groups
3) Slow Learning Groups
The three Coloring depicts the following levels of Experiencing Learners groups:
Refer ANNEXTURE – A
FOR
PERSONALIZED
ASSESSMENT TEST (PAT)
NOTE:
The mode of conduct of the PAT Assessment is based on the time and
resource availability.
That is it is either OFF-LINE or ON-LINE mode.
INDEX
SL No. Topic PAGE NO.
4 ToggleButton 17
5 RadioButtons 27
6 ListView
32
7 ComboBox 55
8 ChoiceBox 60
9 Text Controls 65
10 ScrollPane. 67
Layouts
– FlowPane – HBox and VBox –
BorderPane – StackPane – GridPane.
Menus – Basics – Menu – Menu bars –
MenuItem.
TAKE :- PERSONALIZED ASSESSMENT TEST (PAT) -I
UNIT – V
NOTE:
➔ Important Topic
→ Less Important
➔ → Not Important
Graphics programming
• Java contains support for graphics that enable programmers to visually enhance
applications.
• Java contains many more sophisticated drawing capabilities as part of the Java 2D
API.
Swing
• Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight
components.
• The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
JAVAFX
Uses
Students who wish to get hands-on an amazing GUI development framework - JavaFX
Users who wish to learn GUI and desktop application development using Java
Benefits
• JavaFX is based on a scene graph model that is superior to models used by
Java 2D and Swing
• JavaFX performs well
• JavaFX has properties and binding
• You don’t have to abandon your Swing code to begin using JavaFX
• JavaFX Scene Builder is a great tool for creating JavaFX UIs
• JavaFX includes 3D.
1. Event Basics
Event Properties
Every event includes the information described in Table 1-1.
Property Description
Source Origin of the event, with respect to the location of the event in the event
dispatch chain. The source changes as the event is passed along the chain.
Target Node on which the action occurred and the end node in the event dispatch
chain. The target does not change, however if an event filter consumes the
event during the event capturing phase, the target will not receive the event.
• For example, the MouseEvent class includes information such as which button
was pushed, the number of times the button was pushed, and the position of the
mouse.
Package javafx.event
Provides basic framework for FX events, their delivery and handling.
See: Description
Interface Summary
Interface Description
EventDispatchChain Represents a chain of EventDispatcher objects, which can
dispatch an Event.
EventDispatcher An EventDispatcher represents an event dispatching and
processing entity.
EventHandler<T extends Event> Handler for events of a specific class / type.
EventTarget Represents an event target.
Class Summary
Class Description
ActionEvent An Event representing some type of action.
Event Base class for FX events.
EventType<T extends Event> This class represents a specific event type associated with an Event.
WeakEventHandler<T extends Event> Used in event handler registration in place of its associated event
handler
Event Types
• An event type is an instance of the EventType class.
• Event types further classify the events of a single event class.
• For example, the KeyEvent class contains the following event types:
• KEY_PRESSED
• KEY_RELEASED
• KEY_TYPED
• Event types are hierarchical. Every event type has a name and a super type.
For example, the name of the event for a key being pressed
is KEY_PRESSED, and the super type is KeyEvent.ANY.
The super type of the top-level event type is null. Figure 1-1 shows a subset of the
hierarchy.
• In the subtypes, the event type ANY is used to mean any event type in the event
class. For example, to provide the same response to any type of key event,
use KeyEvent.ANY as the event type for the event filter or event handler.
Event Targets
a) Target Selection
• When an action occurs, the system determines which node is the target based on
internal rules:
• For key events, the target is the node that has focus.
• For mouse events, the target is the node at the location of the cursor. For
synthesized mouse events, the touch point is considered the location of the cursor.
• For continuous gesture events that are generated by a gesture on a touch screen,
the target is the node at the center point of all touches at the beginning of the
gesture. For indirect gesture events that are generated by a gesture on something
other than a touch screen, such as a trackpad, the target is the node at the location
of the cursor.
• For swipe events that are generated by a swipe on a touch screen, the target is the
node at the center of the entire path of all of the fingers. For indirect swipe events,
the target is the node at the location of the cursor.
• For touch events, the default target for each touch point is the node at the location
first pressed. A different target can be specified using the ungrab(), grab(),
or grab(node) methods for a touch point in an event filter or event handler.
• If more than one node is located at the cursor or touch, the topmost node is
considered the target. For example, if a user clicks or touches the triangle shown
in Figure 1-2, the triangle is the target, not the rectangle that contains the circle
and the triangle.
• When a mouse button is pressed and the target is selected, all subsequent mouse
events are delivered to the same target until the button is released.
• Similarly for gesture events, from the start of the gesture to the completion of the
gesture, gesture events are delivered to the target identified at the beginning of the
gesture.
• The default for touch events is to deliver the events to the initial target node that
was identified for each touch point, unless the target is modified using
the ungrab(), grab(), or grab(node) methods.
b) Route Construction
• The initial event route is determined by the event dispatch chain that was created
in the implementation of the buildEventDispatchChain() method of the selected
event target.
• For example, if a user clicks the triangle shown in Figure 1-2, the initial route is
shown by the gray nodes in Figure 1-3. When a scene graph node is selected as an
event target, the initial event route set in the default implementation of
the buildEventDispatchChain() method in the Node class is a path from the stage
to itself.
Figure 1-3 Event Dispatch Chain
The route can be modified as event filters and event handlers along the route process the
event.
Also, if an event filter or event handler consumes the event at any point, some nodes on
the initial route might not receive the event.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
Button btn = new Button();
btn.setLayoutX(100);
btn.setLayoutY(80);
btn.setText("Hello World");
btn.setOnAction(new EventHandler<ActionEvent>() {
Figure 4-1 is the screen that is shown when the Keyboard Example is started.
• The user interface consists of four letters, each in its own square, which represent
the corresponding keyboard key.
• The first key on the screen is highlighted, which indicates that it has the focus.
• Use the left and right arrow keys on the keyboard to move the focus to a different
key on the screen.
When the Enter key is pressed, the key on the screen with the focus changes to red.
When the Enter key is released, the key on the screen returns to its previous color. When
the key for a letter that matches one of the keys on the screen is pressed, the matching
key on the screen changes to red, and returns to its previous color when the key is
released. When a key that does not match any key on the screen is pressed, nothing
happens. Figure 4-2 shows the screen when the A key has focus and the D key on the
keyboard is pressed.
keyEvent.consume();
}
}
};
keyNode.setOnKeyPressed(keyEventHandler);
keyNode.setOnKeyReleased(keyEventHandler);
}
• The keyboard node has two handlers that handle key events that are not consumed
by a key node handler.
• The first handler changes the color of the key node that matches the key pressed.
The second handler responds to the left and right arrow keys and moves the focus.
• Example 4-4 shows the installEventHandler() method that defines the handlers for
the keyboard node.
keyEvent.consume();
}
}
};
keyboardNode.setOnKeyPressed(keyEventHandler);
keyboardNode.setOnKeyReleased(keyEventHandler);
keyboardNode.addEventHandler(KeyEvent.KEY_PRESSED,
new EventHandler<KeyEvent>() {
public void handle(
final KeyEvent keyEvent) {
handleFocusTraversal(
keyboardNode,
keyEvent);
}
});
}
The two handlers for the key-pressed event are considered peer handlers. Therefore,
even though each handler consumes the event, the other handler is still invoked.
textBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
System.out.println("Key Pressed: " + ke.getText());
}
});
textBox.setOnKeyReleased(new EventHandler<KeyEvent>() {
public void handle(KeyEvent ke) {
System.out.println("Key Released: " + ke.getText());
}
});
Mouse Events
Convenience methods for registering event handlers for mouse events include
setOnMouseEntered, setOnMouseExited, and setOnMousePressed.
circle.setOnMouseEntered(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse entered");
}
});
circle.setOnMouseExited(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse exited");
}
});
circle.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
System.out.println("Mouse pressed");
}
});
To see how similar event handlers are used, run the Ensemble sample, which is
available in the JavaFX samples that can be downloaded from the JDK Demos and
Samples section of the Java SE Downloads page.
The Ensemble sample also provides the source code for the event handlers.
Controls:
Stage
Scene
Scene Graph
• All visual components (controls, layouts etc.) must be attached to a scene to be
displayed, and that scene must be attached to a stage for the whole scene to be
visible.
• The total object graph of all the controls, layouts etc. attached to a scene is called
the scene graph.
Nodes
Controls
• JavaFX controls are JavaFX components which provide some kind of control
functionality inside a JavaFX application.
• For instance, a button, radio button, table, tree etc.
• For a control to be visible it must be attached to the scene graph of
some Scene object.
• Controls are usually nested inside some JavaFX layout component that manages
the layout of controls relative to each other.
• Accordion
• Button
• CheckBox
• ChoiceBox
• ColorPicker
• ComboBox
• DatePicker
• Label
• ListView
• RadioButton
• Slider
• Spinner
• SplitMenuButton
• SplitPane
• TableView
• TabPane
• TextArea
• TextField
• TitledPane
• ToggleButton
• ToolBar
• TreeTableView
• TreeView
JAVAFX - Controls
BUTTONS CONTROL:
1. Checkbox,
2. ToggleButton
3. RadioButtons
4. ToggleButton
5. RadioButtons
LIST AND COMBO CONTROLS
1. ListView
2. ComboBox
3. ChoiceBox
4. Checkbox
5. ListView
6. ComboBox
Layouts
• JavaFX layouts are components which contains other components inside them.
• The layout component manages the layout of the components nested inside it.
• JavaFX layout components are also sometimes called parent components because
they contain child components, and because layout components are subclasses of
the JavaFX class javafx.scene.Parent.
• A layout component must be attached to the scene graph of some Scene object to
be visible.
• Group
• Region
• Pane
• HBox
• VBox
• FlowPane
• BorderPane
• StackPane
• TilePane
• GridPane
• AnchorPane
• TextFlow
Nested Layouts
TEXT CONTROLS
JavaFX Text
• The JavaFX Text control can display a text inside a JavaFX GUI.
• The JavaFX Text control is represented by the JavaFX
class javafx.scene.text.Text .
•
• You can set the font to be used by the Text control, text size, font decorations and
many other things.
• Since the JavaFX Text control is a subclass of the JavaFX Shape class, the Text
class has all the same methods available that other JavaFX Shape objects do
- e.g. fill and stroke color and style.
• The JavaFX Text control is also a subclass of the JavaFX Node class,
o so the Text class also has all the same methods available as any other
JavaFX Node has, meaning you can set effects on it etc.
}
}
Set Text
You can set the text of a JavaFX Text object via its setText() method.
Here is an example of setting the text of a JavaFX Text control via setText():
Text text = new Text();
text.setText("This is the text to display");
Set Font
You can set the font of a JavaFX Text control via its setFont() method.
Here is an example of setting the font of a JavaFX Text object via its setFont() method:
Text text = new Text("Some Text");
text.setFont(Font.font("Arial"));
This example sets the font to be used by the Text control to render the text to be of the
font family Arial.
The JavaFX Font class used in this example is the javafx.scene.text.Font class.
The Font class actually also lets you specify the font weight and font size.
Here is the example above, modified to also set font weight and font size for the JavaFX
Text control:
Text text = new Text("Some Text");
Here is an example of setting the fill color of a JavaFX Text control via setFill():
text.setFill(Color.YELLOW);
Here is an example of setting the stroke color of a JavaFX Text control via setStroke():
text.setStroke(Color.GREEN);
You can set the X and Y position of a Text control via its methods setX() and setY().
Text Origin
The JavaFX Text control has an origin which controls how the text is displayed relative
to the Y position of the Text control. You set the origin using the
The VPos class contains the following constants you can choose between:
i) VPos.BASELINE
ii) VPos.BOTTOM
iii) VPos.CENTER
iv) VPos.TOP
i) VPos.BASELINE means that the Y position of the Text control is interpreted to mean
the Y baseline of the displayed text.
The text is displayed just above the baseline, with some characters extending below the
baseline.
ii) VPos.BOTTOM means that the Y position of the Text control is interpreted to mean
the bottom the displayed text. This is lower than BASELINE.
iii) VPos.CENTER means that the Y position of the Text control is interpreted to mean
the center of the text vertically.
iv) VPos.TOP means that the Y position of the Text control is interpreted to mean the
top of the text vertically.
Multiline Text
The JavaFX Text control will break the text it displays on to multiple lines based on
these rules:
i) If the text contains a line break ( \n ) .
ii) If the text width exceeds a wrapping width set on the Text control.
The Text control will break the text before "Line" because the String contains a line
break character.
Here is an example of setting a text wrapping width on the JavaFX Text control:
Text text = new Text("This is a longer JavaFX text.");
text.setWrappingWidth(80);
• The JavaFX Text control will attempt to break the text between words.
• Thus, if after a specific word the text width is wider than the wrapping
width,
the Text control will wrap the text before that word that makes the
text wider than the wrapping width.
Text Strikethrough
• The JavaFX Text control enables you to apply a strikethrough decoration to
the text it displays. You enable the strikethrough decoration via the
Text setStrikethrough() method,
passing a value of true as parameter.
A parameter value of false will disable the strikethrough effect.
Text Underline
The JavaFX Text control enables you to apply an underline decoration to the text it
displays.
You enable the underline decoration via the Text setUnderline() method, passing a value
of true as parameter.
A parameter value of false will disable the underline decoration.
Here are examples of setting both LCD and GRAY as font smoothing technique on a
JavaFX Text control:
text.setFontSmoothingType(FontSmoothingType.GRAY);
text.setFontSmoothingType(FontSmoothingType.LCD);
Which of the two font smoothing techniques fits best to your application you will have
to experiment with.
JavaFX Fonts
Jakob Jenkov
Last update: 2020-11-14
The JavaFX Font class, java.scene.text.Font, enables you to load different Fonts for use in your
JavaFX applications. A font is a text style. All text rendered with the same font will look
similar. In this JavaFX Font tutorial I will show you how to load and set fonts in JavaFX.
To use fonts in JavaFX you must create a JavaFX Font instance. The easiest way to create a
JavaFX Font instance is to use the static factory methods in the Font class. The following
example shows how to create JavaFX Font instances using the many variations of the Font
class static factory methods:
Once you have created a JavaFX Font instance you use it by setting it on whatever JavaFX
component capable of using a Font. For instance, you can set it on a JavaFX Text control.
Here is an example of setting a Font instance on a Text control:
Precisely how a Font object is applied to a given JavaFX control depends on the specific
JavaFX control. In the JavaFX Text example the Font object is applied via the
Text setFont() method, as shown above.
The JavaFX Font class provides two methods that can list the font families and font names and
installed on the system the JavaFX application is running on. These methods are
the getFamilies() and getFontNames() methods. Here are some examples of calling these
methods:
Both font family names and font names can be used when creating a Font instance. Provide
either the font family name or font name in the Font factory method fontFamily parameter.
To see the actual names, loop through the lists above and print out their names, like this:
BUTTONS
JavaFX Button
A JavaFX Button control enables a JavaFX application to have some action executed when the
application user clicks the button. The JavaFX Button control is represented by the
class javafx.scene.control.Button . A JavaFX Button can have a text and an icon on it which
indicate to the user what clicking the button will do.
Creating a Button
You create a button control by creating an instance of the Button class. Here is a
JavaFX Button instantiation example:
The text to be displayed on the button is passed as parameters to the Button constructor.
For a JavaFX Button to be visible the button object must be added to the scene graph. This
means adding it to a Scene object, or as child of a layout which is attached to a Scene object.
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class ButtonExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
Notice that the Button is added directly to the Scene object. Normally you would nest
the Button inside a layout component of some kind. I have left that out here to keep the
example simple. See the tutorials about layout components to see how they work.
The result of running the above JavaFX Button example is an application that looks like this:
Notice that the button takes up all the space available in the window. That is why it is hard to
see the edges of the button. When a JavaFX button is added to a layout component you can
more easily see the edges of the button.
Button Text
There are two ways to set the text of a JavaFX button. The first way is to pass the text to
the Button constructor. You have already seen this in earlier examples.
The second way to set the button text is by calling the setText() method on the Button instance.
This can be done after the Button instance is created. Thus it can be used to change the text of
a Button that is already visible. Here is an example how how calling setText() on a
JavaFX Button looks:
You can set the text size of a JavaFX Button. You do so using the CSS property -fx-text-size.
This CSS property is explained in the section about Button CSS Styling
The JavaFX Button control supports text wrapping of the button text. By text wrapping is
meant that if the text is too long to be displayed on a single line inside the button, the text is
broken onto multiple lines.
You enable text wrapping on a JavaFX Button instance using the method setWrapText().
The setWrapText() method takes a single boolean parameter. If you pass a value
of true to setWrapText() then you enable text wrapping. If you pass a value
of false to setWrapText() then you disable text wrapping. Here is an example that enables text
wrapping on a JavaFX button:
button.setWrapText(true);
Here is a screenshot of two JavaFX buttons one of which has text wrapping enabled:
Button Font
You can specify what font the text on a JavaFX Button should be rendered with via
its setFont() method. You can read more about creating fonts in my JavaFX Fonts tutorial.
Here is an example of setting a font on a JavaFX Button:
button.setFont(font);
A JavaFX Button can be set into a default mode. When a Button is in default mode it is
rendered differently, so the user can see that this is the default button. On Windows, the
Button's background color changes, although I guess that also depends on the color theme used
in the application etc. and may change in future versions of JavaFX.
The default button is intended to be used for the "default choice" in a dialog or form. Thus, it
becomes easier for the user to select the choice that the user is most likely making most often.
The default button of a dialog or form has some additional keyboard shortcuts to help the user
click it:
• Windows + Linux
o If no other button has focus, pressing the ENTER keyboard key will activate the
default button.
o If the default button has focus, pressing the ENTER keyboard key will activate
the default button.
• Mac
o Only the default button can be activated by pressing the ENTER keyboard key.
All other buttons are activated by pressing the the SPACE keyboard key.
Setting a JavaFX Button as the default button is done via its setDefaultButton() method. Here is
an example of setting a JavaFX button as default button:
button.setDefaultButton(true);
Setting a JavaFX Button in cancel mode (as cancel button) is done via
its setCancelButton() method. Here is an example of setting a JavaFX Button in cancel mode:
buttonDefault.setCancelButton(true);
Button Image
It is possible to display an image inside a button next to the button text. The
JavaFX Button class contains a constructor that can take a Node as extra parameter. Here is a
JavaFX label example that adds an image to the button using an JavaFX
ImageView component:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import java.io.FileInputStream;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
The result of running the above JavaFX Button example is an application that looks like this:
Button Size
The JavaFX Button class contains a set of methods you can use to set the button size. The
methods controlling the button size are:
button.setMinWidth()
button.setMaxWidth()
button.setPrefWidth()
button.setMinHeight()
button.setMaxHeight()
button.setPrefHeight()
button.setMinSize()
button.setMaxSize()
button.setPrefSize()
The methods setMinWidth() and setMaxWidth() sets the minimum and maximum width the
button should be allowed to have. The method setPrefWidth() sets the preferred width of the
button. When there is space enough to display a button in its preferred width, JavaFX will do
so. If not, JavaFX will scale the button down until it reaches its minimum width.
The methods setMinHeight() and setMaxHeight() sets the minimum and maximum height the
button should be allowed to have. The method setPrefHeight() sets the preferred height of the
button. When there is space enough to display a button in its preferred height, JavaFX will do
so. If not, JavaFX will scale the button down until it reaches its minimum height.
The methods setMinSize(), setMaxSize() and setPrefSize() sets both width and height for the
button in a single call. Thus, these methods takes both a width and a height parameter. For
instance, calling
button.setMaxSize(100, 200);
is equivalent to calling
button.setMaxWidth(100);
button.setMaxHeight(200);
Here is a screenshot of two JavaFX buttons. The first button has the default size calculated
from its button text and the layout component it is nested inside. The second button has a
preferred width of 200 and height of 48 set on it:
Button Events
In order to respond to the click of a button you need to attach an event listener to
the Button object. Here is how that looks:
button.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent actionEvent) {
//... do something in here.
}
});
Here is how attaching a click event listener looks with a Java Lambda expression:
button.setOnAction(actionEvent -> {
//... do something in here.
});
Finally, let us see a full example that changes the text of a JavaFX Label when the button is
clicked:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
button.setOnAction(value -> {
label.setText("Clicked!");
});
Button Mnemonic
You can set a mnemonic on a JavaFX Button instance. A mnemonic is a keyboard key which
activates the button when pressed in conjunction with the ALT key. Thus, a mnemonic is a
keyboard shortcut to activating the button. I will explain how to activate a button via its
mnemonic later.
The mnemonic for a button is specified inside the button text. You mark which key is to be
used as mnemonic by placing an underscore character (_) in front of the character in the button
text you want to set as mnemonic for that button. The underscore character will not be
displayed in the button text. Here is an example setting a mnemonic for a button:
button.setMnemonicParsing(true);
button.setText("_Click");
Notice that it is necessary to first call setMnemonicParsing() on the button with a value of true.
This instructs the button to parse mnemonics in the button text. If you call this method with a
value of false instead, the underscore character in the button text will just show up as text, and
will not be interpreted as a mnemonic.
The second line sets the text _Click on the button. This tells the button to use the key c as
mnemonic. Mnemonics are case insensitive, so it does not have to be an a uppercase C that
activates the button.
To activate the button you can now press ALT-C (both at the same time). That will activate the
button just as if you had clicked it with the mouse.
You can also first press the ALT key once. That will show the mnemonic of the button in the
button text. You can then press the c key. If you press ALT and then ALT again, the mnemonic
is first shown, then hidden again. When the mnemonic is visible you can activate the button
with the mnemonic key alone, without ALT pressed at the same time. When the mnemonic is
not visible you have to press both ALT and the mnemonic key at the same time to activate the
button.
Here are two screenshots showing what it looks like when the mnemonic is invisible and
visible:
You can style a JavaFX button using CSS styles. The JavaFX Button control supports the
following CSS styles:
-fx-border-width
-fx-border-color
-fx-background-color
-fx-font-size
-fx-text-fill
This example sets the style directly on the button via the setStyle() method, but you can also
style a JavaFX button via style sheets. See my JavaFX CSS Styling tutorial for more
information about using CSS stylesheets with JavaFX.
Here is a JavaFX button example which creates 4 different buttons. Each button has a CSS style
set on them. After the code example I have included a screenshot of how the buttons look with
the given styling.
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Button Experiment 1");
The first button has both the -fx-border-width and -fx-border-color CSS properties set. This
results in a 5 pixel wide red border for the button.
The second button has the -fx-background-color CSS property set. This results in a green
background color for the button.
The third button has the -fx-font-size CSS property set. This results in a button with a text that
is 2 times as big as normal.
The fourth button has the -fx-text-fill CSS property set. This results in a button with a blue text
color.
You can combine the CSS styles for a JavaFX button simply by setting multiple CSS properties
on it, like the first button in the example above has.
Disable Button
You can disable a JavaFX Button via its setDisable() method. The setDisable() method takes
a boolean parameter which specify if the button should be disabled or not. A value
of true means the button will be disabled, and a value of false means it will not be disabled -
which means enabled. Here is an example of disabling a JavaFX Button via
its setDisable() method:
button.setDisable(true);
button.setDisable(false);
Button FXML
It is possible to declare a JavaFX Button inside a JavaFX FXML file. I will not explain FXML
in every detail here. Click on the link in the first sentence to read more about how FXML
works. I will just show you the parts of FXML related to the JavaFX Button control. Here is a
very simple FXML file example that shows how to declare a Button:
It is the <Button> element that declares the Button control. The fx:id attribute can be used to
wire up the declared Button to a Button member variable inside an FXML Controller object.
The text attribute is used to set the corresponding text property value in the Button instance
created for this Button declaration. That is the text displayed on the button.
The onAction attribute is used to link the Button's onAction event to a method in the FXML
controller object. In this example it is the method named buttonClicked() in the FXML
controller.
Here is how the corresponding FXML controller object's class looks. Notice the name of
the button1 Button member variable matches the fx:id attribute value in the FXML file. This
member variable must be public, by the way. Notice also the method buttonClicked() which is
referenced from the Button onAction attribute in the FXML file.
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
@FXML
public void buttonClicked(Event e){
this.button1ClickCount++;
System.out.println(text);
button1.setText(text);
}
And here is the full JavaFX app that loads the FXML file and creates the FXML controller etc.
:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.File;
import java.net.URL;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(scene);
Button Transformations
You can add JavaFX transformations to a JavaFX Button such as scaling, rotation, translation
etc. You add transformation objects to a JavaFX Button like this:
button.getTransforms().add(scaleTransformation);
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
button.setText("Click me!");
button.setOnAction((event) -> {
System.out.println("Button clicked!");
});
button.getTransforms().add(scaleTransformation);
VBox vbox = new VBox(button);
Scene scene = new Scene(vbox);
primaryStage.setScene(scene);
primaryStage.setWidth(512);
primaryStage.setHeight(256);
primaryStage.show();
}
}
JavaFX ToggleButton
A JavaFX ToggleButton is a button that can be selected or not selected. Like a
button that stays in when you press it, and when you press it the next time it comes
out again. Toggled - not toggled. The JavaFX ToggleButton is represented by the
class javafx.scene.control.ToggleButton .
Creating a ToggleButton
You create a JavaFX ToggleButton by creating an instance of
the ToggleButton class. Here is an example of creating a
JavaFX ToggleButton instance:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
The application resulting from running the above example code is illustrated in the
following two screenshots. The first screenshot shows a ToggleButton which is not
pressed, and the second screenshot shows the same ToggleButton pressed
(selected, activated etc.):
ToggleButton Text
You can set or change the text of a JavaFX ToggleButton via its setText() method.
Here is an example of changing the text of a JavaFX ToggleButton via setText():
toggleButton.setText("New Text");
ToggleButton Font
You can set the font to use to render the button text of a JavaFX ToggleButton via
its setFont() method. You can read more about creating fonts in my JavaFX
Fonts tutorial. Here is an example of setting the font of a JavaFX ToggleButton:
toggleButton.setFont(arialFontBold36);
ToggleGroup
You can group JavaFX ToggleButton instances into a ToggleGroup.
A ToggleGroup allows at most one ToggleButton to be toggled (pressed) at any time.
The ToggleButton instances in a ToggleGroup thus functions similarly to radio buttons.
toggleButton1.setToggleGroup(toggleGroup);
toggleButton2.setToggleGroup(toggleGroup);
toggleButton3.setToggleGroup(toggleGroup);
toggleButton4.setToggleGroup(toggleGroup);
Here is a full example that adds the 4 ToggleButton instances to a ToggleGroup, and
adds them to the scene graph too:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
toggleButton1.setToggleGroup(toggleGroup);
toggleButton2.setToggleGroup(toggleGroup);
toggleButton3.setToggleGroup(toggleGroup);
toggleButton4.setToggleGroup(toggleGroup);
ToggleButton selectedToggleButton =
(ToggleButton) toggleGroup.getSelectedToggle();
JavaFX RadioButton
Creating a RadioButton
You create a JavaFX RadioButton using its constructor. Here is a
JavaFX RadioButton instantiation example:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
The application resulting from running this example looks like this:
ToggleGroup
You can group JavaFX RadioButton instances into a ToggleGroup.
A ToggleGroup allows at most one RadioButton to be selected at any time.
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
radioButton1.setToggleGroup(radioGroup);
radioButton2.setToggleGroup(radioGroup);
radioButton3.setToggleGroup(radioGroup);
radioButton4.setToggleGroup(radioGroup);
The application resulting from running this example looks like this:
RadioButton selectedRadioButton =
(RadioButton) toggleGroup.getSelectedToggle();
• Registering a filter for a super-type event to provide common handling for subtype events
Figure 3-1 is the screen that is shown when the Draggable Panels example is started. The user interface consists of three
panels. Each panel contains different UI controls. At the bottom of the screen is a check box that controls whether the panels
can be dragged.
Description of "Figure 3-1 Initial Screen for the Draggable Panels Example"
If the check box is not selected, clicking any of the controls in the panels generates a response from the control. If the check
box is selected, the individual controls do not respond to mouse clicks. Instead, clicking anywhere within a panel and
dragging the mouse moves the entire panel, enabling you to change the position of the panels as shown in Figure 3-2.
wrapGroup.addEventFilter(
MouseEvent.ANY,
new EventHandler<MouseEvent>() {
if (dragModeActiveProperty.get()) {
mouseEvent.consume();
}
}
});
wrapGroup.addEventFilter(
MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>() {
if (dragModeActiveProperty.get()) {
dragContext.mouseAnchorX = mouseEvent.getX();
dragContext.mouseAnchorY = mouseEvent.getY();
dragContext.initialTranslateX =
node.getTranslateX();
dragContext.initialTranslateY =
node.getTranslateY();
});
wrapGroup.addEventFilter(
MouseEvent.MOUSE_DRAGGED,
new EventHandler<MouseEvent>() {
if (dragModeActiveProperty.get()) {
node.setTranslateX(
dragContext.initialTranslateX
+ mouseEvent.getX()
- dragContext.mouseAnchorX);
node.setTranslateY(
dragContext.initialTranslateY
+ mouseEvent.getY()
- dragContext.mouseAnchorY);
});
return wrapGroup;
Filters for the following events are defined and registered for each panel:
• MouseEvent.ANY. This filter processes all mouse events for the panel. If the Drag Mode check box is selected, the filter
consumes the event, and the child nodes, which are the UI controls within the panel, do not receive the event. If the check
box is not selected, the control at the location of the mouse cursor processes the event.
• MouseEvent.MOUSE_PRESSED. This filter processes only mouse-pressed events for the panel. If the Drag Mode check
box is selected, the current location of the mouse is stored.
• MouseEvent.MOUSE_DRAGGED. This filter processes only mouse-dragged events for the panel. If the Drag Mode check
box is selected, the panel is moved.
Note that a panel has three registered filters. Filters for specific event types are invoked before super-type events, so the
filters for MouseEvent.MOUSE_PRESSED and MouseEvent.MOUSE_DRAGGED are invoked before the filter
for MouseEvent.ANY.
JavaFX CheckBox
Creating a CheckBox
You create a JavaFX CheckBox control via the CheckBox constructor. Here is a
JavaFX CheckBox instantiation example:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class CheckBoxExperiments extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("CheckBox Experiment 1");
The application resulting from running this code looks like this:
By default a CheckBox is not allowed to be in the indeterminate state. You can set if
a CheckBox is allowed to be in an indeterminate state using the
method setAllowIndeterminate(). Here is an example of allowing the indeterminate
state for a CheckBox:
checkBox1.setAllowIndeterminate(true);
Note, that if a CheckBox is not in the indeterminate state, it is either selected or not
selected, which can be seen via its isSelected() method
JavaFX ChoiceBox
The JavaFX ChoiceBox control enables users to choose an option from a
predefined list of choices. The JavaFX ChoiceBox control is represented by the
class javafx.scene.control.ChoiceBox . This JavaFX ChoiceBox tutorial will explain
how to use the ChoiceBox class.
Creating a ChoiceBox
You create a ChoiceBox simply by creating a new instance of the ChoiceBox class.
Here is a JavaFX ChoiceBox instantiation example:
ChoiceBox choiceBox = new ChoiceBox();
choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");
Here is an example showing how to add a JavaFX ChoiceBox to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ChoiceBox Experiment 1");
choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");
The application resulting from running this example would look similar to this:
choiceBox.getItems().add("Choice 1");
choiceBox.getItems().add("Choice 2");
choiceBox.getItems().add("Choice 3");
choiceBox.setOnAction((event) -> {
int selectedIndex = choiceBox.getSelectionModel().getSelectedIndex();
Object selectedItem = choiceBox.getSelectionModel().getSelectedItem();
System.out.println("Selection made: [" + selectedIndex + "] " + selectedItem);
System.out.println(" ChoiceBox.getValue(): " + choiceBox.getValue());
});
JavaFX ComboBox
The JavaFX ComboBox control enables users to choose an option from a
predefined list of choices, or type in another value if none of the predefined choices
matches what the user want to select. The JavaFX ComboBox control is
represented by the class javafx.scene.control.ComboBox . This JavaFX ComboBox
tutorial will explain how to use the ComboBox class.
Creating a ComboBox
You create a ComboBox simply by creating a new instance of the ComboBox class. Here
is a JavaFX ComboBox instantiation example:
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
Here is an example showing how to add a JavaFX ComboBox to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ComboBox Experiment 1");
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
The application resulting from running this example would look similar to this:
Making the ComboBox Editable
A ComboBox is not editable by default. That means, that by default the user cannot
enter anything themselves, but only choose from the predefined list of options. To
make a ComboBox editable you must call the setEditable() method of the ComboBox.
Here is an example making a JavaFX ComboBox editable:
comboBox.setEditable(true);
Once the ComboBox is editable the user can type in values into the ComboBox. The
entered value is also read via the getValue() method as explained earlier. The
following screenthot shows a JavaFX ComboBox which is editable, and with a custom
value entered:
comboBox.getItems().add("Choice 1");
comboBox.getItems().add("Choice 2");
comboBox.getItems().add("Choice 3");
comboBox.setOnAction((event) -> {
int selectedIndex = comboBox.getSelectionModel().getSelectedIndex();
Object selectedItem = comboBox.getSelectionModel().getSelectedItem();
JavaFX ListView
The JavaFX ListView control enables users to choose one or more options from a
predefined list of choices. The JavaFX ListView control is represented by the
class javafx.scene.control.ListView . This JavaFX ListView tutorial will explain how
to use the ListView class.
Creating a ListView
You create a ListView simply by creating a new instance of the ListView class. Here
is a JavaFX ListView instantiation example:
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
Here is an example showing how to add a JavaFX ListView to the scene graph:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
The application resulting from running this example would look similar to this
screenshot:
Notice how the ListView shows multiple options by default. You can set a height
and width for a ListView, but you cannot set explicitly how many items should be
visible. The height determines that based on the height of each item displayed.
If there are more items in the ListView than can fit into its visiible area,
the ListView will add scroll bars so the user can scroll up and down over the items.
ObservableList selectedIndices =
listView.getSelectionModel().getSelectedIndices();
The OberservableList will contain Integer objects representing the indexes of the
selected items in the ListView.
Here is a full JavaFX example with a button added which reads the selected items
of the ListView when clicked:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
button.setOnAction(event -> {
ObservableList selectedIndices =
listView.getSelectionModel().getSelectedIndices();
for(Object o : selectedIndices){
System.out.println("o = " + o + " (" + o.getClass() + ")");
}
});
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
Once you have set the SelectionMode.MULTIPLE on the ListView selection model, the
user can select multiple items in the ListView by holding down SHIFT or CTRL
when selecting additional items after the first selected item.
Here is a full JavaFX example that shows how to set a ListView into multiple
selection mode, including a button which when clicked will write out the indices of
the selected items in the ListView :
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("ListView Experiment 1");
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
listView.getItems().add("Item 1");
listView.getItems().add("Item 2");
listView.getItems().add("Item 3");
button.setOnAction(event -> {
ObservableList selectedIndices =
listView.getSelectionModel().getSelectedIndices();
for(Object o : selectedIndices){
System.out.println("o = " + o + " (" + o.getClass() + ")");
}
});
JavaFX TextField
A JavaFX TextField control enables users of a JavaFX application to enter text
which can then be read by the application. The JavaFX TextField control is
represented by the class javafx.scene.control.TextField .
Creating a TextField
You create a TextField control by creating an instance of the TextField class. Here
is a JavaFX TextField instantiation example:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
The result of running the above JavaFX TextField example is an application that
looks like this:
Getting the Text of a TextField
You can get the text entered into a TextField using its getText() method which
returns a String. Here is a full example that shows a TextField and a Button and
which reads the text entered into the TextField when the button is clicked:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
button.setOnAction(action -> {
System.out.println(textField.getText());
});
textField.setText("Initial value");
JavaFX PasswordField
• Creating a PasswordField
• Adding a PasswordField to the Scene Graph
• Getting the Text of a PasswordField
Jakob Jenkov
Last update: 2016-05-19
Creating a PasswordField
You create a PasswordField control by creating an instance of
the PasswordField class. Here is a JavaFX PasswordField instantiation example:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("PasswordField Experiment 1");
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("PasswordField Experiment 1");
button.setOnAction(action -> {
System.out.println(passwordField.getText());
});
JavaFX TextArea
JavaFX TextArea control enables users of a JavaFX application to enter text
spanning multiple lines, which can then be read by the application. The JavaFX
TextArea control is represented by the class javafx.scene.control.TextArea .
Creating a TextArea
You create a TextArea control by creating an instance of the TextArea class. Here is
a JavaFX TextArea instantiation example:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TextArea Experiment 1");
TextArea textArea = new TextArea();
The result of running the above JavaFX TextArea example is an application that
looks like this:
Here is a full example that shows a TextArea and a Button and which reads the text
entered into the TextArea when the button is clicked:
package com.jenkov.javafx.controls;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TextArea Experiment 1");
button.setOnAction(action -> {
System.out.println(textArea.getText());
textArea.setText("Clicked!");
});
textArea.setText("New Text");
JavaFX Accordion
The JavaFX Accordion control is a container control which can contain several
sections internally, each of which can have their content expanded or collapsed.
The Accordion control is implemented by the JavaFX
class javafx.scene.control.Accordion. The section displayed inside it are made up
of JavaFX TitledPane controls. Here is a screenshot of a JavaFX Accordion control:
Notice that none of the sections are expanded. You can expand a section by
clicking on the little triangle next to the title for each section. Expanding a section
will reveal its content. Here is a screenshot of a JavaFX Accordion with a section
expanded:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AccordionExample extends Application {
accordion.getPanes().add(pane1);
accordion.getPanes().add(pane2);
accordion.getPanes().add(pane3);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Create an Accordion
Before you can use the JavaFX Accordion control you must first instantiate it. You
instantiate it simply using the Java new command, like this:
accordion.getPanes().add(pane1);
accordion.getPanes().add(pane2);
accordion.getPanes().add(pane3);
primaryStage.setScene(scene);
primaryStage.show();
Text Controls
1. ScrollPane
2. BorderPane
3. StackPane
4. GridPane
5. FlowPane
6. HBox and VBox
JavaFX ScrollPane
The JavaFX ScrollPane control is a container that has two scrollbars around the
component it contains if the component is larger than the visible area of the
ScrollPane. The scrollbars enable the user to scroll around the component shown
inside the ScrollPane, so different parts of the component can be seen. The
JavaFX ScrollPane controls is represented by the JavaFX
class javafx.scene.control.ScrollPane. Here is a screenshot of a
JavaFX ScrollPane with a JavaFX ImageView inside:
Create a ScrollPane
To use a JavaFX ScrollPane you must first create a ScrollPane instance. Here is an
example of creating a JavaFX ScrollPane instance:
scrollPane.setContent(imageView);
ScrollPane Viewport
The visible part of a JavaFX ScrollPane is called the ScrollPane viewport. As you
scroll around the content displayed inside the ScrollPane using the scrollbars, the
viewport is moved around the content too, making different parts of the content
visible.
Pannable ScrollPane
By default the user can only navigate around the content displayed in a
JavaFX ScrollPane using its scrollbars. However, it is possible to make a
JavaFX ScrollPane pannable. A pannable ScrollPane enables the user to navigate its
content by holding down the left mouse button and move the mouse around. This
will have the same effect as using the scrollbars. However, using panning you can
move the content along both X and Y axis simultaneously. This is not possible
using the scrollbars, where the user can only operate one scrollbar at a time.
scrollPane.pannableProperty().set(true);
Fit To Width
The JavaFX ScrollPane fitToWidth property can make the ScrollPane fit its content to
the width of the ScrollPane viewport. To do so, the fitToWidth property must be set
to the value true. This property is ignored if the content node is not resizable. Here
is an example of setting the JavaFX ScrollPane fitToWidth property to true:
scrollPane.fitToWidthProperty().set(true);
Fit To Height
The JavaFX ScrollPane fitToHeight property can make the ScrollPane fit its content
to the height of the ScrollPane viewport. To do so, the fitToHeight property must be
set to the value true. This property is ignored if the content node is not resizable.
Here is an example of setting the JavaFX ScrollPane fitToHeight property to true:
scrollPane.fitToHeightProperty().set(true);
scrollPane.hbarPolicyProperty().setValue(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.vbarPolicyProperty().setValue(ScrollPane.ScrollBarPolicy.NEVER);
The above example removes the vertical and horizonal scrollbar from
the ScrollPane. Without the scrollbars the user cannot use them to scroll around the
content of the ScrollPane. However, if the ScrollPane is in pannable mode (see
earlier sections in this JavaFX ScrollPane tutorial) the user can still grab the
content and scroll around it with the mouse.
JavaFX TitledPane
The JavaFX TitledPane control is a container control which displays its content
inside a a pane (box) which at the top contains a title - hence the name TitledPane.
The TitledPane control is implemented by the javafx.scene.control.TitledPane class.
In this JavaFX TitledPane tutorial we will look at how to use the TitledPane control.
Here is a JavaFX TitledPane screenshot showing how it looks:
A TitledPane can be collapsed so only the title bar is visible. This functionality is
used inside the JavaFX Accordion control. The TitledPane can of course be
expanded too. I will show how that works later in this tutorial.
Notice the second line in the code example. This is the line that creates
the TitledPane instance. Notice how the title to display in the TitledPane is passed as
a parameter to the constructor. Notice also, how the content to display, a JavaFX
Node, is also passed as a parameter to the constructor. In this example the content
is just a simple JavaFX Label.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
Label label = new Label("The content inside the TitledPane");
TitledPane titledPane = new TitledPane("The Title", label);
primaryStage.show();
}
}
titledPane.setExpanded(true);
titledPane.setExpanded(false);
Disable Collapse
It is possible to disable the collapse functionality of a JavaFX TitledPane. You do so
by calling its setCollapsible() method, passing a value of false as parameter. Here
is how switching off the collapsible functionality of a TitledPane looks:
titledPane.setCollapsible(false);
JavaFX Pane
The JavaFX Pane class is a layout container which can contain other JavaFX
components internally, and lay them out. Actually, the JavaFX Pane class does not
actually provide any layout algorithm. The Pane class simply displays the
components it contains at the locations the components themselves want to be
located. In other words, the Pane class uses the layoutX and layoutY specified by its
child components to determine where to display them.
If you repeat the last line multiple times, you will add multiple Label instances to the
Pane. Just keep in mind, that unless you change the layoutX and / or layoutY
properties of the added Labels, all the Label instances will be displayed in the same
X and Y position - meaning on top of each other.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
primaryStage.setScene(scene);
primaryStage.show();
}
}
JavaFX FlowPane
A JavaFX FlowPane is a layout component which lays out its child components
either vertically or horizontally, and which can wrap the components onto the next
row or column if there is not enough space in one row. The JavaFX FlowPane
layout component is represented by the class javafx.scene.layout.FlowPane
Creating a FlowPane
You create a JavaFX FlowPane via its constructor. Here is a
JavaFX FlowPane instantiation example:
flowpane.getChildren().add(button1);
flowpane.getChildren().add(button2);
flowpane.getChildren().add(button3);
package com.jenkov.javafx.layouts;
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HBox Experiment 1");
flowpane.getChildren().add(button1);
flowpane.getChildren().add(button2);
flowpane.getChildren().add(button3);
flowpane.setHgap(10);
flowpane.setVgap(10);
When added to the example earlier, the resulting application would look like this:
Notice the horizontal and vertical gaps between the buttons now.
Orientation
By default the components in a FlowPane are layed out horizontally, wrapping onto
the next horizontal line when there is no longer space enough inside the FlowPane to
show more components horizontally.
flowpane.setOrientation(Orientation.VERTICAL);
JavaFX GridPane
A JavaFX GridPane is a layout component which lays out its child components in a
grid. The size of the cells in the grid depends on the components displayed in the
GridPane, but there are some rules. All cells in the same row will have the same
height, and all cells in the same column will have the same width. Different rows
can have different heights and different columns can have different widths.
The JavaFX GridPane is different from the TilePane in that a GridPane allows
different size of cells, whereas a TilePane makes all tiles the same size.
The number of rows and columns in a GridPane depends on the components added
to it. When you add a component to a GridPane you tell in what cell (row, column)
the component should be inserted, and how many rows and columns the
component should span.
Creating a GridPane
You create a JavaFX GridPane via its constructor. Here is a
JavaFX GridPane instantiation example:
gridPane.add(button1, 0, 0, 1, 1);
gridPane.add(button2, 1, 0, 1, 1);
gridPane.add(button3, 2, 0, 1, 1);
gridPane.add(button4, 0, 1, 1, 1);
gridPane.add(button5, 1, 1, 1, 1);
gridPane.add(button6, 2, 1, 1, 1);
The first parameter of the add() method is the component (node) to add to
the GridPane.
The second and third parameter of the add() method is the column index and row
index of the cell in which the component should be displayed. Column and row
indexes start from 0.
The fourth and fifth parameter of the add() method are the oclumn span and row
span of the component, meaning how many rows and columns the component
should extend to. Column span and row span works similarly
to colspan and rowspan in an HTML table.
package com.jenkov.javafx.layouts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("GridPane Experiment");
gridPane.add(button1, 0, 0, 1, 1);
gridPane.add(button2, 1, 0, 1, 1);
gridPane.add(button3, 2, 0, 1, 1);
gridPane.add(button4, 0, 1, 1, 1);
gridPane.add(button5, 1, 1, 1, 1);
gridPane.add(button6, 2, 1, 1, 1);
The application resulting from this application looks like the following screen shots.
Spanning Multiple Rows and Columns
To see how to make a component span multiple columns and rows, look at this
modification of the 6 buttons added to the GridPane:
gridPane.add(button1, 0, 0, 2, 2);
gridPane.add(button2, 2, 0, 1, 1);
gridPane.add(button3, 2, 1, 1, 1);
gridPane.add(button4, 0, 2, 1, 1);
gridPane.add(button5, 1, 2, 1, 1);
gridPane.add(button6, 2, 2, 1, 1);
Notice how the first button added is given a column span and row span of 2. Notice
how the rest of the buttons are added outside of the top left 2 x 2 columns. The
layout resulting from these settings looks like this:
gridPane.setHgap(10);
gridPane.setVgap(10);
When added to the example earlier, the resulting application would look like this:
Notice the horizontal and vertical gaps between the buttons. If there were no gaps
set on the GridPane the buttons would have been positioned next to each other.
JavaFX HBox
The JavaFX HBox component is a layout component which positions all its child
nodes (components) in a horizontal row. The Java HBox component is represented
by the class javafx.scene.layout.HBox .
Create an HBox
You create an HBox using its constructor like this:
This HBox example will layout the two Button instances next to each other in a
horizontal row.
Here is an example that attaches a JavaFX HBox with the two Button instances to the
scene graph:
package com.jenkov.javafx.layouts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage)
throws Exception {
The result of running the above JavaFX HBox example is an application that looks
like this:
Notice that the two Button controls are kept on the same horizontal row even if there
is not enough space to show them in their fully preferred widths. The buttons do not
"wrap" down on the next line.
This example sets the spacing between the controls in the HBox layout component
to 20.
You can also set the space between the nested controls using
the setSpacing() meethod, like this:
hbox.setSpacing(50);
This example will set the spacing between nested controls to 50.
This example sets the margin around the Button inside the HBox to 10 on each
side.
hbox.setAlignment(Pos.BASELINE_CENTER);
This example will make the HBox position its child nodes along the baseline
(vertically) of the vertical line, and from the center of the line and out (horizontally).
HBox.setHgrow(button1, Priority.ALWAYS);
The Priority class contains the following constants you can use to set the expansion
policy:
1. Policy.ALWAYS
2. Policy.SOMETIMES
3. Policy.NEVER
Please keep in mind that the HBox will only have extra horizontal space available if
the HBox is wider than the sum of the preferred widths of its children.
fillHeight
The JavaFX HBox fillHeight property can be used to tell the HBox control whether
it should expand the height of its children to fill out the whole height of the HBox, or
keep its children at their preferred heights.
The fillHeight property only affects child components which heights can actually
change. For instance, a Button does not change its height by default. It's max
height is set to its preferred height. However, you can override that by setting the
max height of the Button, or any other component you want to nest inside the
HBox, to a value different than its preferred value.
hbox.setFillHeight(true);
JavaFX VBox
The JavaFX VBox component is a layout component which positions all its child
nodes (components) in a vertical column - on top of each other. The JavaFX VBox
component is represented by the class javafx.scene.layout.VBox . In this JavaFX
VBox tutorial I will take a deeper look at the various options the VBox component
has for the layout of controls.
Create a VBox
To use the JavaFX VBox component you must first create an instance of the VBox
class. You create a VBox instance using its constructor like this:
This VBox example will layout the two Button instances one on top of the other in a
vertical column.
Here is an example that attaches a JavaFX VBox with the two Button instances to the
scene graph:
package com.jenkov.javafx.layouts;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage)
throws Exception {
The result of running the above JavaFX VBox example is an application that looks
like this:
Child Node Spacing
In the earlier example the VBox positioned the nodes (button controls) right under
the other. You can make the VBox insert some space between its nested controls by
providing the space in the VBox constructor. Here is an example of setting the space
between nested controls in an VBox:
This example sets the spacing between the controls in the VBox layout component
to 20.
You can also set the space between the nested controls using
the setSpacing() method, like this:
vbox.setSpacing(50);
This example will set the spacing between nested controls to 50.
vbox.setAlignment(Pos.BASELINE_CENTER);
This example will make the VBox position its child nodes along the baseline
(vertically) of the vertical line, and from the center of the line and out (horizontally).
The JavaFX VBox control supports the following alignment options:
Center Horizontally
You can use the child node alignment features to horizontally center the child
nodes of a VBox. Here is an example showing how to center the child nodes of a
VBox horizontally:
vbox.setAlignment(Pos.BASELINE_CENTER);
This example sets the margin around the Button inside the VBox to 10 on each
side.
VBox.setVgrow(button, Priority.ALWAYS);
The Priority class contains the following constants you can use to set the expansion
policy:
1. Policy.ALWAYS
2. Policy.SOMETIMES
3. Policy.NEVER
Please keep in mind that the VBox will only have extra vertical space available if
the child nodes do not have the same preferred height, or if you explicitly set a
preferred height on the VBox that is larger than the preferred height of its child
nodes.
fillWidth
The JavaFX VBox fillWidth property can be used to tell the VBox control whether it
should expand the width of its children to fill out the whole width of the VBox, or
keep its children at their preferred widths.
The fillWidth property only affects child components which widths can actually
change. For instance, a Button does not change its width by default. It's max width
is set to its preferred width. However, you can override that by setting the max
width of the Button, or any other component you want to nest inside the VBox, to a
value different than its preferred value.
vbox.setFillWidth(true);
VBox CSS
Like many other JavaFX controls the VBox component can be styled via CSS. You
set the CSS styles of the JavaFX VBox component via its setStyle() method.
Styling JavaFX controls via CSS is covered in more detail in the JavaFX CSS
Styling tutorial, but I will briefly explain how to style a JavaFX VBox here. Here is
an example of setting the CSS styles of a JavaFX VBox component:
vbox.setStyle("-fx-padding: 16;");
CSS
Description
Property
Sets the padding between the edge of the VBox and the edge of
-fx-padding
the outermost child nodes.
-fx-border- Sets the border style of the VBox, in case you want a visible
style border around it.
-fx-border-
Sets the border width.
width
-fx-border- Sets the border insets.
insets
-fx-border-
Sets the border radius (of corners).
radius
-fx-border-
Sets the border color.
color
VBox FXML
You can define a JavaFX VBox from inside a JavaFX FXML document. Here is an
example of how a VBox FXML definition looks:
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<GridPane xmlns:fx="http://javafx.com/fxml"
fx:controller="sample.Controller"
alignment="center" hgap="10" vgap="10">
<VBox>
<Label>Text inside VBox</Label>
</VBox>
</GridPane>
Here are some of the most commonly used VBox XML element attributes:
• border
• alignment
• fillWidth
MENUS
MENU CONTROLS
1. Menu Basics
2. Menu bars
3. MenuItem
MENUBAR
JavaFX MenuBar
The JavaFX MenuBar provides JavaFX applications with a visual drop down menu
similar to that most desktop applications have at the top of their application window.
The JavaFX MenuBar is represented by the class javafx.scene.control.MenuBar . Here
is an example screenshot of what a JavaFX MenuBar can look like:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX App");
primaryStage.setScene(scene);
primaryStage.show();
}
}
Notice how the MenuBar is added to the root layout (VBox) of the JavaFX scene. This
places the MenuBar at the top of the application window.
Note that the above example does not add any menus or menu items to
the MenuBar, so if you run the example you will not actually see the MenuBar. We will
see how to add menus and menu items in the following sections.
As you can see, there is only a single menu in the MenuBar titled "Menu 1" . This
menu has no menu items nested under it. We will see how to add menu items to
a Menu in the following sections.
Menu Graphics
You can set a graphic icon for a Menu by calling its setGraphic() method. The graphic
icon will be displayed next to the text label of the menu. Here is an example of
setting a graphic icon for a JavaFX Menu instance:
Menu Events
A JavaFX Menu instance can fire several events which you can listen for in your
application. The most commonly used events are:
• onShowing
• onShown
• onHiding
• onHidden
When a Menu is clicked with the mouse it shows its contents. This action fires the
event onShowing before the Menu starts showing its menu items. Once the menu is
fully visible the onShown event is fired.
When an shown (open) Menu is clicked with the mouse it hides its contents again.
This action fires the event onHiding before the Menu starts hiding its menu items.
Once the menu is fully hidden the onHidden event is fired.
You can set Menu event listeners for the events above using the
methods setOnShowing(), setOnShown(), setOnHiding() and setOnHidden(). Here is an
example of setting event listeners for these events on a JavaFX Menu :
The Menu event listeners set above only print out a message to the console when
the events fired. You could do something more advanced in case you needed to.
Here is what the resulting JavaFX MenuBar would look like, if used in a JavaFX
application:
MenuItem Graphics
You can add an icon to a menu item. You add a graphic icon to a MenuItem by
calling its setGraphic() method, passing as parameter the graphic you want to use
for the given MenuItem. Here is an example that adds images to the menu items
created in the example in the previous section:
menu.getItems().add(menuItem1);
menu.getItems().add(menuItem2);
Here is how a JavaFX MenuBar looks with graphic icons added to its menu items:
MenuItem Events
The MenuBar configurations created in the previous examples do not react if you
select any of the menu items. In order to respond to the selection of a MenuItem you
must set an event listener on the MenuItem. Here is an example of adding an event
listener to a JavaFX MenuItem:
menuItem1.setOnAction(e -> {
System.out.println("Menu Item 1 Selected");
});
Submenus
The JavaFX MenuBar supports multiple layers of menus. A menu nested inside
another menu is called a submenu. The Menu class extends the MenuItem class and
can therefore be used as a menu item inside another Menu instance. Here is an
example that creates a single JavaFX menu with a submenu inside:
The JavaFX MenuBar resulting from the above example will look similar to this:
menu.getItems().add(checkMenuItem);
The Menu instance then need to be added to a MenuBar to be visible, as you have
seen in earlier examples. Here is how the resulting menu looks, with the check
menu menu item checked:
Radio Menu Item
The JavaFX MenuBar also supports radio menu items. Radio menu items are menu
items of which only one of a set of menu items can be selected - just like
standard JavaFX radio buttons.
menu.getItems().add(choice1Item);
menu.getItems().add(choice2Item);
menu.getItems().add(choice3Item);
Here is how the JavaFx menu resulting from this example code looks:
Menu Item Separators
The MenuBar supports menu item separators. A separator is a horizontal line that
separates groups of menu items. A separator is often used to signal to users what
menu items are related to each other.
menu.getItems().add(item1);
menu.getItems().add(separator);
menu.getItems().add(item2);
The CustomMenuItem class has a setContent() method which you can use to set the
custom JavaFX control to show in the menu. Here is an example that shows both
a JavaFX Button and a JavaFX Slider as custom menu items:
Notice the call to CustomMenuItem setHideOnClick() with the value false as parameter.
This is done to keep the menu open while the user interacts with the custom menu
item control. If you set the value to true the menu will close as soon as the user
clicks the control the first time, making further interaction impossible. For normal
menu items you actually do want the menu to close immediately, but for some
custom menu items you may not want that. The menu can still be closed by clicking
on the menu title again.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
menuItem3.setOnAction((event) -> {
System.out.println("Choice 3 clicked!");
});
contextMenu.getItems().addAll(menuItem1,menuItem2,menuItem3);
textArea.setContextMenu(contextMenu);
primaryStage.setScene(scene);
primaryStage.setTitle("JavaFX App");
primaryStage.show();
}
}
Create a ContextMenu
To use a JavaFX ContextMenu you must first create a ContextMenu instance. Here is
an example of creating a JavaFX ContextMenu:
menuItem3.setOnAction((event) -> {
System.out.println("Choice 3 clicked!");
});
contextMenu.getItems().addAll(menuItem1,menuItem2,menuItem3);
textArea.setContextMenu(contextMenu);
MENU CONTROLS
4. Menus
5. Basics
6. Menu
7. Menu bars
8. MenuItem
Charts
• AreaChart
• BarChart
• BubbleChart
• LineChart
• PieChart
• ScatterChart
• StackedAreaChart
• StackedBarChart
2D Graphics
JavaFX contains features that makes it easy to draw 2D graphics on the screen.
3D Graphics
• JavaFX contains features that make it easy to draw 3D graphics on the screen.
Audio
• JavaFX contains features that make it easy to play audio in JavaFX applications.
• This is typically useful in games or educational applications.
Video
JavaFX contains features that makes it easy to play video in JavaFX applications. This is
typically useful in streaming applications, games or educational applications.
WebView