Java Reference
In-Depth Information
When the user presses the secondary mouse button, the lambda expression defined in the setOnMousePressed
method is invoked. Calling the show() method in the manner used in the snippet causes the ContextMenu to be
displayed on the screen at the location in which the mouse was pressed. A ContextMenu must have an owner, either a
Node or a Stage , for it to be displayed, which is why the Stage object was passed into the show() method.
Creating a SplitMenuButton
Very similar to the MenuButton , the SplitMenuButton pops up a ContextMenu when the down arrow is clicked. In
addition, when the main part of the SplitMenuButton is clicked, the behavior is that of a Button . Both of these
behaviors are demonstrated in Steps 22 and 23 of the previous exercise when interacting with the SplitMenuButton
shown in Figure 6-9 . The following snippet from Listing 6-12 realizes these behaviors:
MenuItem splitMenuA = new MenuItem("MenuItem A");
splitMenuA.setOnAction(e -> System.out.println(e.getEventType()
+ " occurred on Menu Item A"));
MenuItem splitMenuB = new MenuItem("MenuItem B");
SplitMenuButton splitMenuButton = new SplitMenuButton(splitMenuA, splitMenuB);
splitMenuButton.setText("SplitMenuButton");
splitMenuButton.setOnAction(e -> System.out.println(e.getEventType()
+ " occurred on SplitMenuButton"));
Let's move away from the button-like UI controls and turn our attention to some UI controls that accept text
input, starting with the TextField .
Defining a TextField
In Step 25 of the exercise, as you entered text into the TextField shown in Figure 6-9 , the contents of the TextField
were printed to the Java console each time the contents changed (e.g., as characters were typed into the TextField ).
The following snippet from Listing 6-12 creates the TextField and implements these behaviors:
final TextField textField = new TextField();
textField.setPromptText("Enter user name");
textField.setPrefColumnCount(16);
textField.textProperty().addListener((ov, oldValue, newValue) -> {
System.out.println("TextField text is: " + textField.getText());
});
To detect when the text property of the TextField has changed, the code in this snippet adds a ChangeListener
to the text property. The new value of the text property is then printed to the Java console in the body of the lambda
expression.
Using a PasswordField
The PasswordField extends the TextField class, and its purpose is to mask the characters that are typed into it. In
Step 26 of the exercise, when you entered text into the PasswordField shown in Figure 6-9 and subsequently caused
the PasswordField to lose focus, the contents of the PasswordField were printed to the Java console. The following
snippet from Listing 6-12 creates the PasswordField and implements these behaviors:
final PasswordField passwordField = new PasswordField();
passwordField.setPromptText("Enter password");
passwordField.setPrefColumnCount(16);
 
Search WWH ::




Custom Search