Java Reference
In-Depth Information
For the last requirements relating to the image viewer application, simple controls
are generated that allow the users to view the next or previous image. I emphasize
“simple” controls because JavaFX contains two other methods for creating custom con-
trols. One way (CSS styling) is discussed later, in Recipe 15-5. To explore the other al-
ternative, refer to the Javadoc on the Skin and Skinnable APIs.
The simple buttons in this example are created using Java FX's
javafx.scene.shape.Arc
to build the left and right arrows on top of a small
transparent rounded rectangle called
javafx.scene.shape.Rectangle
. Next,
an
EventHandler
that listens to mouse-pressed events is added via a lambda expres-
sion, and it will load and display the appropriate image based on the enums
But-
tonMove.PREV
and
ButtonMove.NEXT
.
When instantiating a generic class with a type variable between the
<
and
>
sym-
bols, the same type variable will be defined in
the handle()
's signature. When im-
plementing the event handler logic, you determine which button was pressed and then
return the index into the
imageFiles
list of the next image to display. When loading
an image using the
Image
class, it is possible to load images from the file system or
from a
URL
. The following code instantiates an
EventHandler<MouseEvent>
lambda expression to display the previous image in the
imageFiles
list:
leftButton.addEventHandler(MouseEvent.MOUSE_PRESSED,
(MouseEvent me) -> {
int indx = gotoImageIndex(ButtonMove.PREV);
if (indx > -1) {
String namePict = imageFiles.get(indx);
namePict = filePrefix + namePict;
final Image image = new Image(namePict);
currentImageView.setImage(image);
}
});
The right button's (
rightButton
) event handler is identical. The only thing dif-
ferent is that it must determine whether the previous or next button was pressed via the
ButtonMove
enum. This information is passed to the
gotoImageIndex()
meth-
od to determine whether an image is available in that direction.
To finish the image viewer application, you bind the rectangular button's control to
the scene's width and height, which repositions the control as the user resizes the win-
dow. Here, you bind the
translateXProperty()
to the scene's width property by