0% found this document useful (0 votes)
4 views

Frontend Development with JavaFX and Kotlin: Build State-of-the-Art Kotlin GUI Applications Peter Späth pdf download

The document is a promotional overview of the book 'Frontend Development with JavaFX and Kotlin' by Peter Späth, which focuses on building advanced GUI applications using Kotlin and JavaFX. It includes links to download the book and additional resources related to Kotlin development. The document also lists other related eBooks available for download on the same website.

Uploaded by

hwammayyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Frontend Development with JavaFX and Kotlin: Build State-of-the-Art Kotlin GUI Applications Peter Späth pdf download

The document is a promotional overview of the book 'Frontend Development with JavaFX and Kotlin' by Peter Späth, which focuses on building advanced GUI applications using Kotlin and JavaFX. It includes links to download the book and additional resources related to Kotlin development. The document also lists other related eBooks available for download on the same website.

Uploaded by

hwammayyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Frontend Development with JavaFX and Kotlin:

Build State-of-the-Art Kotlin GUI Applications


Peter Späth pdf download

https://ebookmeta.com/product/frontend-development-with-javafx-
and-kotlin-build-state-of-the-art-kotlin-gui-applications-peter-
spath/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Pro Android with Kotlin: Developing Modern Mobile Apps


with Kotlin and Jetpack, 2nd Edition Peter Späth

https://ebookmeta.com/product/pro-android-with-kotlin-developing-
modern-mobile-apps-with-kotlin-and-jetpack-2nd-edition-peter-
spath/

Beginning Kotlin: Build Applications with Better Code,


Productivity, and Performance 1st Edition Ted Hagos

https://ebookmeta.com/product/beginning-kotlin-build-
applications-with-better-code-productivity-and-performance-1st-
edition-ted-hagos/

Pro Spring 6 with Kotlin : An In-depth Guide to Using


Kotlin APIs in Spring Framework 6 1st Edition Peter
Späth

https://ebookmeta.com/product/pro-spring-6-with-kotlin-an-in-
depth-guide-to-using-kotlin-apis-in-spring-framework-6-1st-
edition-peter-spath/

Her Bare Alien Alien Mating Agency Book 3 1st Edition


Lacey Carter Andersen

https://ebookmeta.com/product/her-bare-alien-alien-mating-agency-
book-3-1st-edition-lacey-carter-andersen/
Explainable Artificial Intelligence for Cyber Security
Mohiuddin Ahmed

https://ebookmeta.com/product/explainable-artificial-
intelligence-for-cyber-security-mohiuddin-ahmed/

Adventures in Improv Quilts 5th Edition Cindy Grisdela

https://ebookmeta.com/product/adventures-in-improv-quilts-5th-
edition-cindy-grisdela/

The Gospel of Juas Iscariot and Other Sacred Gospels


2023rd Edition Judas Iscariot

https://ebookmeta.com/product/the-gospel-of-juas-iscariot-and-
other-sacred-gospels-2023rd-edition-judas-iscariot/

Organizing Solutions for People with ADHD Tips and


Tools to Help You Take Charge of Your Life 3rd Edition
Susan C. Pinsky

https://ebookmeta.com/product/organizing-solutions-for-people-
with-adhd-tips-and-tools-to-help-you-take-charge-of-your-
life-3rd-edition-susan-c-pinsky/

The Materiality of Magic An artifactual investigation


into ritual practices and popular beliefs Ceri
Houlbrook (Editor)

https://ebookmeta.com/product/the-materiality-of-magic-an-
artifactual-investigation-into-ritual-practices-and-popular-
beliefs-ceri-houlbrook-editor/
Supramolecular Chemistry on Surfaces 2D Networks and 2D
Structures 1st Edition Neil R. Champness (Editor)

https://ebookmeta.com/product/supramolecular-chemistry-on-
surfaces-2d-networks-and-2d-structures-1st-edition-neil-r-
champness-editor/
Frontend
Development with
JavaFX and Kotlin
Build State-of-the-Art Kotlin
GUI Applications

Peter Späth
Frontend Development with JavaFX and Kotlin
Peter Späth

Frontend Development
with JavaFX and Kotlin
Build State-of-the-Art Kotlin GUI Applications
Peter Späth
Leipzig, Sachsen, Germany

ISBN-13 (pbk): 978-1-4842-9716-2 ISBN-13 (electronic): 978-1-4842-9717-9


https://doi.org/10.1007/978-1-4842-9717-9

Copyright © 2023 by Peter Späth


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned,
specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by
similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of
a trademarked name, logo, or image, we use the names, logos, and images only in an editorial fashion and to the benefit of the
trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such,
is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors
nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher
makes no warranty, express or implied, with respect to the material contained herein.

Managing Director, Apress Media LLC: Welmoed Spahr


Acquisitions Editor: Celestin Suresh John
Development Editor: Laura Berendson
Coordinating Editor: Mark Powers

Cover designed by eStudioCalamar


Cover image by Jerryyaar Designer on Pixabay (www.pixabay.com)

Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004, U.S.A. Phone 1-
800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media,
LLC is a California LLC, and the sole member (owner) is Springer Science + Business Media Finance Inc. (SSBM Finance
Inc). SSBM Finance Inc. is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint, paperback, or audio rights,
please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also
available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/
bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub (https://
github.com/Apress). For more detailed information, please visit https://www.apress.com/gp/services/source-code.

Paper in this product is recyclable


Contents

1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Gradle for JavaFX and Kotlin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
A HelloWorld Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Setting Up for Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Setting Up for IntelliJ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Kotlin and Java Interoperability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
A Note About Kotlin Utilities for JavaFX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
A Note About FXML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
A Note About Downloading JavaFX Releases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Build Setup for This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2 Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Why you Should use Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
One-Way and Two-Way Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Custom Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
About Observable Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3 Stages and Scenes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
About Screens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Using Stages and the Application Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Dialog-Like Stages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
The JavaFX Application Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
About Scenes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Position and Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Camera . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Cursor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Mnemonic and Accelerators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Focus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Node Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Snapshots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Fill and Other Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Mouse Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Mouse Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

v
vi Contents

Mouse Drag Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52


Gestures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4 Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
StackPane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
VBox and HBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
FlowPane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
GridPane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
TilePane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
BorderPane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
AnchorPane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Styling Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Adding Stylesheets to the Whole Scene . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Adding Stylesheets to Individual Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
JavaFX CSS Selectors for Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
JavaFX CSS Properties for Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5 Visual Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Node Coordinate Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Image Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Text Fields and Text Areas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Action Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Button Bars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Toolbars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Checkboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Radio Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Combo Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Sliders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Miscellaneous Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Control Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Scroll Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Accordions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Tab Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Split Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Styling Visual Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6 Lists and Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Lists with ListView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Tables with TableView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Trees with TreeView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Contents vii

7 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
What Events Are and Event Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Event Handlers and Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Drag and Drop Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8 Effects and Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
About Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Animating Your Scenes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Timeline Animations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
9 Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
The JavaFX Concurrency Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
About Kotlin Coroutines for JavaFX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
About the Author

Peter Späth graduated in 2002 as a physicist and soon afterward became an IT consultant, mainly for
Java-related projects. In 2016, he decided to concentrate on writing books on various aspects, but with
a main focus on software development. With two books about graphics and sound processing, three
books on Android app development, and a couple of books about Java, Jakarta EE, and Kotlin, Peter
continues his effort in writing software development-related literature.

ix
About the Technical Reviewer

Massimo Nardone has more than 25 years of experience in security,


web and mobile development, cloud, and IT architecture. His true
IT passions are security and Android. He has been programming
and teaching how to program with Android, Perl, PHP, Java, VB,
Python, C/C++, and MySQL for more than 20 years. He holds a
Master of Science degree in Computing Science from the University
of Salerno, Italy. He has worked as a CISO, CSO, security executive,
IoT executive, project manager, software engineer, research engineer,
chief security architect, PCI/SCADA auditor, and senior lead IT
security/cloud/SCADA architect for many years. His technical skills
include security, Android, cloud, Java, MySQL, Drupal, Cobol, Perl,
web and mobile development, MongoDB, D3, Joomla, Couchbase,
C/C++, WebGL, Python, Pro Rails, Django CMS, Jekyll, Scratch,
and more. He worked as visiting lecturer and supervisor for exercises
at the Networking Laboratory of the Helsinki University of Technol-
ogy (Aalto University). He holds four international patents (PKI, SIP,
SAML, and Proxy areas). He is currently working for Cognizant as
head of cyber security and CISO to help both internally and externally
with clients in areas of information and cyber security, like strategy,
planning, processes, policies, procedures, governance, awareness,
and so forth. In June 2017 he became a permanent member of the
ISACA Finland Chapter Board.
Massimo has reviewed more than 45 IT books for different
publishing companies and is the coauthor of Pro Spring Security:
Securing Spring Framework 5 and Boot 2-based Java Applications
(Apress, 2019), Beginning EJB in Java EE 8 (Apress, 2018), Pro
JPA 2 in Java EE 8 (Apress, 2018), and Pro Android Games (Apress,
2015).

xi
Introduction

Building elegant and highly responsible, responsive, and stable Java client applications (fat clients)
is a highly acceptable approach if security considerations or network availability speaks against
web applications, or maintaining servers and server applications lies out of scope for your project.
Additionally, using Kotlin as a programming language boosts code expressiveness and maintainability,
allowing for a development yielding a clean code approach.
The book introduces JavaFX as a frontend technology and from the very beginning focuses
on using Kotlin instead of Java for coding the program artifacts. Many listings and code snippets
accompany the text, readily allowing for a hands-on learning style.

The Book’s Targeted Audience

The book is for low- to mid-level Java or Kotlin developers with or without JavaFX experience,
wishing to learn how to build JavaFX applications with Kotlin.
The readers will in the end be able to use Kotlin as a language for building basic to moderately
advanced and elaborated apps targeting JavaFX.
Any experience in using JavaFX and frontend coding is not a requirement for reading the book.
Being a Kotlin expert is not necessary either, but having read introductory-level books or studied
online resources is surely helpful. The online documentation of Kotlin and JavaFX also provides
valuable resources you can use as a reference while reading this book.

Source Code

All source code shown or referred to in this book can be found at github.com/apress/frontend-
development-javafx-kotlin.

How to Read This Book

This book should be read sequentially to get the most benefit from it. Of course, you can skip one
or the other chapter if you already gained knowledge elsewhere. Taking its introductory nature, the
book is not meant to present a reference fully covering each and every aspect of Kotlin frontend
programming or JavaFX, so also consulting the online documentation at
https://openjfx.io/
https://openjfx.io/javadoc/19/
https://kotlinlang.org/docs/home.html

xiii
xiv Introduction

while you are reading the book certainly is not a bad idea.
The book is split up into nine chapters. Chapter 1 gives a general introduction and presents hello
world-style programs for Gradle, Eclipse, and IntelliJ.
Chapter 2 talks about using properties as data holders and addresses one- and two-way binding
techniques for connecting controls and data in your program.
Chapter 3 introduces stages and scenes, which serve as primordial containers for visual artifacts.
Chapter 4 talks about containers and ways to lay out and style your scenes.
Chapter 5 handles nodes and controls including styling. These aspects usually constitute the biggest
part of your project work speaking of time budget.
Chapter 6 presents lists and tables, which are particularly important for enterprise-level projects.
Chapter 7 is for summarizing and deepening our knowledge about event handling in JavaFX. This
also includes drag and drop procedures.
Chapter 8 introduces effects and animation, improving user experience and giving your programs
some eye candies.
As a prospect, Chapter 9 briefly introduces concurrency techniques, giving you a starting point for
handling background processing needs.
Getting Started
1

In this chapter, we give a brief introduction to using JavaFX and Kotlin together, and we create “Hello
World”–style projects for the command line, for Eclipse, and for IntelliJ IDEA.

Introduction

JavaFX is the dedicated fat client (desktop application) GUI toolkit for current Java releases. It is
the replacement and successor of the venerable Java Swing technology. This switch happened around
2010, and since then JavaFX has been constantly improved and extended. With JREs up to version
JDK 9, JavaFX was part of the Java distribution—with JDK 11 and later, it has to be installed
separately.
The following features describe JavaFX:

. Built-in controls: Labels, editable text fields, buttons, combo boxes, checkboxes, radio buttons,
menu bars, scrollbars, accordion, tabs, canvas (for drawing shapes and figures), color picker, pag-
ination, 3D graphics (games, science, product presentation), WebView (presenting and interacting
with web contents), dialogs, sliders, spinners, progress bars
. Lists, tables, trees
. Built-in layouts: AnchorPane (anchoring nodes to one of the edges or to the center point),
BorderPane (placing nodes at bottom, top, right, left, center), FlowPane (placing nodes consec-
utively and wrapping at the boundaries), TilePane (same as FlowPane, but with all cells the same
size), GridPane (placing nodes in a grid with cell sizes dynamically calculated and on demand
spanning several rows and columns), VBox (placing nodes in columns), HBox (placing nodes in
rows), StackPane (placing nodes in an overlay fashion)
. Animation (fade, fill, stroke, translate, rotate, scale, . . . ), effects (glow, blend, bloom, blur,
reflection, sepia, shadow, lighting)
. Nodes stylable via CSS
. Some built-in chart widgets
. Flexible and concise data binding via observable properties
. Descriptive layouting via FXML
. Module support (for JDK 9+)

© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023 1
P. Späth, Frontend Development with JavaFX and Kotlin,
https://doi.org/10.1007/978-1-4842-9717-9_1
2 1 Getting Started

. Graphics transformations and coordinate systems


. Media APIs
. Java Swing interoperability
. Comes as a set of JAR modules and native libraries
. An external Scene Builder for graphically creating scenes
. Printing API

In this book, we describe a subset of these features, giving you a starting point for your own
projects.
Using Kotlin as a programming language instead of Java gives a boost to your coding experience.
Just to give you an example, consider a button with a click handler. In Java, you’d write
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});

(255 characters) The very same code written in Kotlin reads


val btn = Button().apply {
text = "Say 'Hello World'"
setOnAction { _ ->
println("Hello World!")
}
}

With 142 characters, this is more than 40% shorter than the Java variant! And besides being shorter,
it is also more expressive and by that easier to understand and easier to maintain.
Using some sufficiently nonobtrusive utility functions, this can even be further reduced to 81
characters in size:
val btn = Button("Say 'Hello World'") {
println("Hello World!")
}

This works by Kotlin’s ability to dynamically add additional constructors to classes.

Gradle for JavaFX and Kotlin

As a build tool, we use Gradle from https://gradle.org/. It is highly flexible, works on any operating
system that provides a Java installation, and by means of plugins or preinstalled components can be
operated from many IDEs.
I first describe the CLI mode for running Gradle builds. This is how you would use it in a server
environment, but it also serves as a good starting point if you want to learn how to use Gradle inside
an IDE workflow.
If not already present, get and install a version 17 JDK. Throughout the book, we will be using
OpenJDK 17, but if chances are good you can also take Oracle’s supported JDK 17 or a higher version
from either Oracle or https://openjdk.org/ without any problems possibly coming up.
Gradle for JavaFX and Kotlin 3

Note Using Oracle’s JDK 17 or higher requires buying a license if you plan to use it for a longer
term; see www.oracle.com/java/.

As a next step, fetch Gradle from https://gradle.org. In this book, we use version 7.6 from https://
gradle.org/next-steps/?version=7.6&format=bin. In order to announce Java to Gradle, either make
sure java and javac (with .bat extension on Windows) are in your PATH, or you have the
environment variable JAVA_HOME point to your JDK installation folder (recommended). To simplify
using Gradle, you can also put GRADLE-INST-DIR/bin (with GRADLE-INST-DIR pointing to your
Gradle folder), or GRADLE-INST-DIR\bin for Windows, on the path.

Note In Linux, environment variables like PATH or JAVA_HOME get set via
export PATH=/bin:/usr/bin:/path/to/my/gradle/bin.
In Windows, you must use the system settings dialog.

In order to check your Gradle installation, in a terminal enter


gradle -version

or, if Gradle is not in the path:


/path/to/gradle -version (Linux)
C:\path\to\gradle.bat -version (Windows)

The output of the command should be similar to


---------------------------------------------------------
Gradle 7.6
---------------------------------------------------------

Build time: 2022-11-25 13:35:10 UTC


Revision: daece9dbc5b79370cc8e4fd6fe4b2cd400e150a8

Kotlin: 1.7.10
Groovy: 3.0.13
Ant: Apache Ant(TM) version 1.10.11 compiled on
July 10 2021
JVM: 17.0.1 (Oracle Corporation 17.0.1+12-39)
OS: Linux 5.15.0-56-generic amd64

Important is the “JVM:” line. The Kotlin version shown does not mean you would not be able to build
applications running under a different Kotlin version—it just tells it is using Kotlin 1.7.10 for its own
purposes.
Next, create a project folder anywhere on your system. For our example project, we call it
HelloWorld. Change into that folder:
cd /path/to/HelloWorld (Linux)
chdir C:\path\to\HelloWorld (Windows)

In order to initialize the Gradle project, enter (one line)


gradle init --dsl groovy --incubating
--insecure-protocol ALLOW --package book.kotlinfx
--project-name kotlinfx --test-framework kotlintest
--type kotlin-application

You can also enter just gradle init, but then you will subsequently be asked for project
coordinates inside the terminal.
4 1 Getting Started

The “init” task creates a simple scaffold project which consists of a main project described by
file settings.gradle and a subproject called “app” in the accordingly named subfolder. The
application can be run by just entering either of
gradle app:run
gradle run

The second variant is possible, because there is just one subproject. By the way, you can list all
possible tasks via gradle tasks or gradle tasks --all, and entering gradle help shows
more info.
Did you notice that two executable files gradlew and gradlew.bat and a folder gradle were
created? This is the Gradle Wrapper, and it is a Gradle installation on its own, and you can henceforth
use it to build the project. Just use gradlew from the wrapper instead of gradle from the Gradle
distribution. You can even delete the main Gradle installation folder at this time, if you like.
It is now time to add JavaFX to the project. In Gradle, the build.gradle file is the main
configuration file for the build process. You can find it inside the app subproject inside the app folder.
Open the file inside a text editor, and inside the plugins { . . . } section, add
plugins {
...
id 'org.openjfx.javafxplugin' version '0.0.13'
}

This plugin adds almost all that is necessary to add JavaFX to a Java or Kotlin project. Kotlin
capabilities were already added during gradle init. We however still need to make sure that
Kotlin compiles for JDK 17 and that JavaFX uses version 19 and allows for using the modules
“javafx.controls” and “javafx.graphics”. For that aim, add at the end of build.gradle
compileKotlin {
kotlinOptions {
suppressWarnings = true
jvmTarget = "17"
}
}
javafx {
version = "19"
modules("javafx.controls", "javafx.graphics")
}

Note JavaFX is separated into different modules. The modules “javafx.base”, “javafx.controls”, and
“javafx.graphics” are essential to almost any JavaFX application. Because both the controls and the
graphics module require the base module, the latter gets implicitly included in any build and can be
omitted from the modules list. For more details, see https://openjfx.io/javadoc/19/

In the next section, we code our little “Hello World” JavaFX with Kotlin application.

A HelloWorld Project

The scaffold project built via gradle init just prints “Hello World!” on the console if run. As a
starter JavaFX project, we instead want to show a little window with a button on it reacting to press
events. To do so, replace the contents of
app/src/main/kotlin/book/kotlinfx/App.kt
Exploring the Variety of Random
Documents with Different Content
elbows resting upon her knees, and her chin upon her thumbs. The
Baron started: the remembrance of his interview with a similar
personage in the same place some three years since, flashed upon
his recollection. He rushed towards the spot, but the form was gone;
—nothing remained but the seat it had appeared to occupy. This, on
examination, turned out to be no stone, but the whitened skull of a
dead horse!—A tender remembrance of the deceased Grey Dolphin
shot a momentary pang into the Baron's bosom; he drew the back
of his hand across his face; the thought of the hag's prediction in an
instant rose, and banished all softer emotions. In utter contempt of
his own weakness, yet with a tremor that deprived his redoubtable
kick of half its wonted force, he spurned the relic with his foot. One
word alone issued from his lips, elucidatory of what was passing in
his mind,—it long remained imprinted on the memory of his faithful
followers,—that word was "Gammon!" The skull bounded across the
beach till it reached the very margin of the stream;—one instant
more, and it would be engulfed for ever. At that moment a loud "Ha!
ha! ha!" was distinctly heard by the whole train to issue from its
bleached and toothless jaws; it sank beneath the flood in a horse
laugh!
Meanwhile Sir Robert de Shurland felt an odd sort of sensation in his
right foot. His boots had suffered in the wars. Great pains had been
taken for their preservation. They had been "soled" and "heeled"
more than once;—had they been "goloshed," their owner might have
defied Fate! Well has it been said that "there is no such thing as a
trifle." A nobleman's life depended upon a question of ninepence.
The Baron marched on; the uneasiness in his foot increased. He
plucked off his boot;—a horse's tooth was sticking in his great toe!
The result may be anticipated. Lame as he was, his lordship, with
characteristic decision, would hobble on to Shurland; his walk
increased the inflammation; a flagon of aqua vitæ did not mend
matters. He was in a high fever; he took to his bed. Next morning
the toe presented the appearance of a Bedfordshire carrot; by
dinner-time it had deepened to beet-root; and when Bargrave, the
leech, at last sliced it off, the gangrene was too confirmed to admit
of remedy. Dame Martin thought it high time to send for Miss
Margaret, who, ever since her mother's death, had been living with
her maternal aunt, the abbess, in the Ursuline convent at Greenwich.
The young lady came, and with her came one Master Ingoldsby, her
cousin-german by the mother's side; but the Baron was too far gone
in the dead-thraw to recognise either. He died as he lived,
unconquered and unconquerable. His last words were—"Tell the old
hag she may go to——." Whither remains a secret. He expired
without fully articulating the place of her destination.
But who and what was the crone who prophesied the catastrophe?
Ay, "that is the mystery of this wonderful history."—Some say it was
Dame Fothergill, the late confessor's mamma; others, St. Bridget
herself; others thought it was nobody at all, but only a phantom
conjured up by conscience. As we do not know, we decline giving an
opinion.
And what became of the Clerk of Chatham?—Mr. Simpkinson avers
that he lived to a good old age, and was at last hanged by Jack
Cade, with his inkhorn about his neck, for "setting boys copies." In
support of this he adduces his name "Emmanuel," and refers to the
historian Shakspear. Mr. Peters, on the contrary, considers this to be
what he calls one of Mr. Simpkinson's "Anacreonisms," inasmuch as,
at the introduction of Mr. Cade's reform measure, the Clerk, if alive,
would have been hard upon two hundred years old. The probability
is, that the unfortunate alluded to was his great-grandson.
Margaret Shurland in due course became Margaret Ingoldsby, her
portrait still hangs in the gallery at Tappington. The features are
handsome, but shrewish, betraying, as it were, a touch of the old
Baron's temperament; but we never could learn that she actually
kicked her husband. She brought him a very pretty fortune in chains,
owches, and Saracen ear-rings; the barony, being a male fief,
reverted to the Crown.
In the abbey-church at Minster may yet be seen the tomb of a
recumbent warrior, clad in the chain-mail of the 13th century.[5] His
hands are clasped in prayer; his legs, crossed in that position so
prized by Templars in ancient, and tailors in modern days, bespeak
him a soldier of the faith in Palestine. Close behind his dexter calf
lies sculptured in bold relief a horse's head; and a respectable
elderly lady, as she shows the monument, fails not to read her
auditors a fine moral lesson on the sin of ingratitude, or to claim a
sympathising tear to the memory of poor "Grey Dolphin!"

FOOTNOTES:
[2] I-run, is a town said to have been so named from something of this sort.
[3] One of the uses to which this mystic chandelier was put, was the protection of
secreted treasure. Blow out all the fingers at one puff and you had the money.
[4] Since the appearance of the first edition of this Legend "the guns" have been
dismounted. Rumour hints at some alarm on the part of the Town Council.
[5] Subsequent to the first appearance of the foregoing narrative, the tomb
alluded to has been opened during the course of certain repairs which the church
has undergone. Mr. Simpkinson, who was present at the exhumation of the body
within, and has enriched his collection with three of its grinders, says the bones of
one of the great toes were wanting. He speaks in terms of great admiration at the
thickness of the skull, and is of opinion that the skeleton is that of a great patriot
much addicted to Lundy-foot.
It is on my own personal reminiscences that I draw for the following
story; the scene of its leading event was most familiar to me in early
life. If the principal actor in it be yet living, he must have reached a
very advanced age. He was often at the Hall, in my infancy, on
professional visits. It is, however, only from those who "prated of his
whereabouts" that I learned the history of his adventure with
THE GHOST.
There stands a City,—neither large nor
small,
Its air and situation sweet and pretty;
It matters very little—if at all—
Whether its denizens are dull or witty,
Whether the ladies there are short or
tall,
Brunettes or blondes, only, there
stands a city!—
Perhaps 'tis also requisite to minute
That there's a Castle and a Cobbler in it.

A fair Cathedral, too, the story goes,


And kings and heroes lie entomb'd
within her;
There pious Saints, in marble pomp
repose,
Whose shrines are worn by knees of
many a Sinner;
There, too, full many an Aldermanic nose
Roll'd its loud diapason after dinner;
And there stood high the holy sconce of
Becket,
—Till four assassins came from France to
crack it.

The Castle was a huge and antique


mound,
Proof against all th' artillery of the
quiver,
Ere those abominable guns were found,
To send cold lead through gallant
warrior's liver.
It stands upon a gently rising ground,
Sloping down gradually to the river,
Resembling (to compare great things
with smaller)
A well-scooped, mouldy Stilton cheese,—
but taller.

The keep, I find, 's been sadly alter'd


lately,
And, 'stead of mail-clad knights, of
honour jealous,
In martial panoply so grand and stately,
Its walls are filled with money-making
fellows,
And stuff'd, unless I'm misinformed
greatly,
With leaden pipes, and coke, and
coals, and bellows;
In short, so great a change has come to
pass,
'Tis now a manufactory of Gas.

But to my tale.—Before this profanation,


And ere its ancient glories were cut
short all,
A poor hard-working Cobbler took his
station
In a small house, just opposite the
portal;
His birth, his parentage, and education,
I know but little of—a strange, odd
mortal;
His aspect, air, and gait, were all
ridiculous;
His name was Mason—he'd been
christened Nicholas.

Nick had a wife possessed of many a


charm,
And of the Lady Huntingdon
persuasion;
But, spite of all her piety, her arm
She'd sometimes exercise when in a
passion;
And, being of a temper somewhat warm,
Would now and then seize, upon small
occasion,
A stick, or stool, or anything that round
did lie,
And baste her lord and master most
confoundedly.

No matter!—'tis a thing that's not


uncommon,
'Tis what we all have heard, and most
have read of,—
I mean, a bruizing, pugilistic woman,
Such as I own I entertain a dread of,
—And so did Nick,—whom sometimes
there would come on
A sort of fear his Spouse might knock
his head off,
Demolish half his teeth, or drive a rib in,
She shone so much in "facers" and in
"fibbing."

"There's time and place for all things,"


said a sage,
(King Solomon, I think,) and this I can
say,
Within a well-roped ring, or on a stage,
Boxing may be a very pretty Fancy,
When Messrs. Burke or Bendigo engage;
—'Tis not so well in Susan, Jane, or
Nancy:—
To get well mill'd by any one's an evil,
But by a lady—'tis the very Devil.

And so thought Nicholas, whose only


trouble,
(At least his worst,) was this his rib's
propensity,
For sometimes from the alehouse he
would hobble,
His senses lost in a sublime immensity
Of cogitation—then he couldn't cobble—
And then his wife would often try the
density
Of his poor skull, and strike with all her
might,
As fast as kitchen-wenches strike a light.

Mason, meek soul, who ever hated strife,


Of this same striking had a morbid
dread,
He hated it like poison—or his wife.
A vast antipathy!—but so he said
And very often, for a quiet life,
On these occasions he'd sneak up to
bed,
Grope darkling in, and, soon as at the
door
He heard his lady—he'd pretend to
snore.

One night, then, ever partial to society,


Nick, with a friend (another jovial
fellow),
Went to a Club—I should have said
Society—
At the "City Arms," once call'd the
Porto Bello;
A Spouting party, which, though some
decry it, I
Consider no bad lounge when one is
mellow;
There they discuss the tax on salt, and
leather,
And change of ministers and change of
weather.

In short, it was a kind of British Forum,


Like John Gale Jones's, erst in
Piccadilly,
Only they managed things with more
decorum,
And the Orations were not quite so
silly;
Far different questions, too, would come
before 'em,
Not always Politics, which, will ye nill
ye,
Their London prototypes were always
willing,
To give one quantum suff. of—for a
shilling.

It more resembled one of later date,


And tenfold talent, as I'm told in Bow
Street,
Where kindlier natured souls do
congregate,
And, though there are who deem that
same a low street,
Yet, I'm assured, for frolicsome debate
And genuine humour it's surpassed by
no street,
When the "Chief Baron" enters, and
assumes
To "rule" o'er mimic "Thesigers" and
"Broughams."

Here they would oft forget their Ruler's


faults,
And waste in ancient lore the midnight
taper,
Inquire if Orpheus first produced the
Waltz,
How Gas-lights differ from the Delphic
Vapour,
Whether Hippocrates gave Glauber's
Salts,
And what the Romans wrote on ere
they'd paper;—
This night the subject of their
disquisitions
Was Ghosts, Hobgoblins, Sprites, and
Apparitions.

One learned gentleman, "a sage grave


man,"
Talk'd of the Ghost in Hamlet,
"sheath'd in steel;"—
His well-read friend, who next to speak
began,
Said, "That was Poetry, and nothing
real;"
A third, of more extensive learning, ran
To Sir George Villiers' Ghost, and Mrs.
Veal;
Of sheeted Spectres spoke with
shorten'd breath,
And thrice he quoted "Drelincourt on
Death."

Nick smoked, and smoked, and trembled


as he heard
The point discuss'd, and all they said
upon it,
How, frequently, some murder'd man
appear'd,
To tell his wife and children who had
done it;
Or how a Miser's ghost, with grisly
beard,
And pale lean visage, in an old Scotch
bonnet,
Wander'd about to watch his buried
money!
When all at once Nick heard the clock
strike One,—he

Sprang from his seat, not doubting but a


lecture
Impended from his fond and faithful
She;
Nor could he well to pardon him expect
her,
For he had promised to "be home to
tea;"
But having luckily the key o' the back
door,
He fondly hoped that, unperceived, he
Might creep up stairs again, pretend to
doze,
And hoax his spouse with music from his
nose.

Vain fruitless hope!—The wearied


sentinel
At eve may overlook the crouching foe,
Till, ere his hand can sound the alarum-
bell,
He sinks beneath the unexpected
blow;
Before the whiskers of Grimalkin fell,
When slumb'ring on her post, the
mouse may go;—
But woman, wakeful woman, 's never
weary,
—Above all, when she waits to thump
her deary.

Soon Mrs. Mason heard the well-known


tread;
She heard the key slow creaking in the
door,
Spied, through the gloom obscure,
towards the bed
Nick creeping soft, as oft he had crept
before;
When, bang, she threw a something at
his head,
And Nick at once lay prostrate on the
floor;
While she exclaim'd with her indignant
face on,—
"How dare you use your wife so, Mr.
Mason?"
Spare we to tell how fiercely she
debated,
Especially the length of her oration,—
Spare we to tell how Nick expostulated,
Roused by the bump into a good set
passion,
So great, that more than once he
execrated,
Ere he crawl'd into bed in his usual
fashion;
—The Muses hate brawls; suffice it then
to say,
He duck'd below the clothes—and there
he lay!

'Twas now the very witching time of


night,
When churchyards groan, and graves
give up their dead,
And many a mischievous, enfranchised
Sprite
Had long since burst his bonds of
stone or lead,
And hurried off, with schoolboy-like
delight,
To play his pranks near some poor
wretch's bed,
Sleeping perhaps serenely as a porpoise,
Nor dreaming of this fiendish Habeas
Corpus.

Not so our Nicholas, his meditations


Still to the same tremendous theme
recurred,
The same dread subject of the dark
narrations,
Which, back'd with such authority, he'd
heard;
Lost in his own horrific contemplations,
He ponder'd o'er each well-
remember'd word;
When at the bed's foot, close beside the
post,
He verily believed he saw—a Ghost!

Plain and more plain the unsubstantial


Sprite
To his astonish'd gaze each moment
grew;
Ghastly and gaunt, it rear'd its shadowy
height,
Of more than mortal seeming to the
view,
And round its long, thin, bony fingers
drew
A tatter'd winding-sheet, of course all
white;—
The moon that moment peeping through
a cloud,
Nick very plainly saw it through the
shroud!

And now those matted locks, which


never yet
Had yielded to the comb's unkind
divorce,
Their long-contracted amity forget,
And spring asunder with elastic force;
Nay, e'en the very cap, of texture coarse,
Whose ruby cincture crown'd that
brow of jet,
Uprose in agony—the Gorgon's head
Was but a type of Nick's up-squatting in
the bed.

From every pore distill'd a clammy dew,


Quaked every limb,—the candle too no
doubt,
En règle, would have burnt extremely
blue,
But Nick unluckily had put it out;
And he, though naturally bold and stout,
In short, was in a most tremendous
stew;—
The room was fill'd with a sulphureous
smell,
But where that came from Mason could
not tell.

All motionless the Spectre stood,—and


now
Its rev'rend form more clearly shone
confest;
From the pale cheek a beard of purest
snow
Descended o'er its venerable breast;
The thin grey hairs, that crown'd its
furrow'd brow,
Told of years long gone by.—An awful
guest
It stood, and with an action of
command,
Beckon'd the Cobbler with its wan right
hand.

"Whence, and what art thou, Execrable


Shape?"
Nick might have cried, could he have
found a tongue,
But his distended jaws could only gape,
And not a sound upon the welkin rung:
His gooseberry orbs seem'd as they
would have sprung
Forth from their sockets,—like a
frightened Ape
He sat upon his haunches, bolt upright,
And shook, and grinn'd, and chatter'd
with affright.

And still the shadowy finger, long and


lean,
Now beckon'd Nick, now pointed to the
door;
And many an ireful glance, and frown,
between,
The angry visage of the Phantom
wore,
As if quite vex'd that Nick would do no
more
Than stare, without e'en asking, "What
d'ye mean?"
THE GHOST.
Because, as we are told,—a sad old joke
too,—
Ghosts, like the ladies, "never speak till
spoke to."

Cowards, 'tis said, in certain situations,


Derive a sort of courage from despair,
And then perform, from downright
desperation,
Much more than many a bolder man
would dare.
Nick saw the Ghost was getting in a
passion,
And therefore, groping till he found the
chair,
Seized on his awl, crept softly out of bed,
And follow'd quaking where the Spectre
led.

And down the winding stair, with


noiseless tread,
The tenant of the tomb pass'd slowly
on,
Each mazy turning of the humble shed
Seem'd to his step at once familiar
grown,
So safe and sure the labyrinth did he
tread
As though the domicile had been his
own,
Though Nick himself, in passing through
the shop,
Had almost broke his nose against the
mop.
Despite its wooden bolt, with jarring
sound,
The door upon its hinges open flew;
And forth the Spirit issued,—yet around
It turn'd as if its follower's fears it
knew,
And, once more beckoning, pointed to
the mound,
The antique Keep, on which the bright
moon threw
With such effulgence her mild silvery
gleam,
The visionary form seem'd melting in her
beam.

Beneath a pond'rous archway's sombre


shade,
Where once the huge portcullis swung
sublime,
'Mid ivied battlements in ruin laid,
Sole, sad memorials of the olden time,
The Phantom held its way,—and though
afraid
Even of the owls that sung their
vesper chime,
Pale Nicholas pursued, its steps
attending,
And wondering what on earth it all would
end in.

Within the mouldering fabric's deep


recess
At length they reach a court obscure
and lone;—
It seem'd a drear and desolate
wilderness,
The blacken'd walls with ivy all
o'ergrown;
The night-bird shriek'd her note of wild
distress,
Disturb'd upon her solitary throne,
As though indignant mortal step should
dare,
So led, at such an hour, to venture there!

—The Apparition paused, and would


have spoke,
Pointing to what Nick thought an iron
ring,
But then a neighbouring chanticleer
awoke,
And loudly 'gan his early matins sing;
And then "it started like a guilty thing,"
As that shrill clarion the silence broke.
—We know how much dead gentlefolks
eschew
The appalling sound of "Cock-a-doodle-
do!"

The vision was no more—and Nick alone



"His streamers waving" in the midnight
wind,
Which through the ruins ceased not to
groan;
—His garment, too, was somewhat
short behind,—
And, worst of all, he knew not where to
find
The ring,—which made him most his
fate bemoan—
The iron ring,—no doubt of some trap
door,
'Neath which the old dead Miser kept his
store.

"What's to be done?" he cried, "'Twere


vain to stay
Here in the dark without a single clue

Oh, for a candle now, or moonlight ray!
'Fore George, I'm vastly puzzled what
to do,"
(Then clapped his hand behind)—"'Tis
chilly too—
I'll mark the spot, and come again by
day.
What can I mark it by?—Oh, here's the
wall—
The mortar's yielding—here I'll stick my
awl!"

Then rose from earth to sky a withering


shriek,
A loud, a long-protracted note of woe,
Such as when tempests roar, and timbers
creak,
And o'er the side the masts in thunder
go;
While on the deck resistless billows
break,
And drag their victims to the gulfs
below;—
Such was the scream when, for the want
of candle,
Nick Mason drove his awl in up to the
handle.
Scared by his Lady's heart-appalling cry,
Vanished at once poor Mason's golden
dream—
For dream it was;—and all his visions
high,
Of wealth and grandeur, fled before
that scream—
And still he listens with averted eye,
When gibing neighbours make "the
Ghost" their theme;
While ever from that hour they all
declare
That Mrs. Mason used a cushion in her
chair!
Confound not, I beseech thee, reader, the subject of the following
monody with the hapless hero of the tea-urn, Cupid, of "Yow-Yow"-
ing memory. Tray was an attached favourite of many years' standing.
Most people worth loving have had a friend of this kind; Lord Byron
says he "never had but one, and here he (the dog, not the
nobleman,) lies!"
THE CYNOTAPH.
Poor Tray charmant!
Poor Tray de mon Ami!

Dog-bury and Vergers.

Oh! where shall I bury my poor dog Tray,


Now his fleeting breath has passed
away?—
Seventeen years, I can venture to say,
Have I seen him gambol, and frolic, and
play,
Evermore happy, and frisky, and gay,
As though every one of his months was
May,
And the whole of his life one long holiday

Now he's a lifeless lump of clay,
Oh! where shall I bury my faithful Tray?

I am almost tempted to think it hard


That it may not be there, in yon sunny
churchyard,
Where the green willows wave O'er
the peaceful grave,
Which holds all that once was honest
and brave,
Kind, and courteous, and faithful, and
true;
Qualities, Tray, that were found in you.
But it may not be—yon sacred ground,
By holiest feelings fenced around,
May ne'er within its hallow'd bound
Receive the dust of a soul-less hound.

I would not place him in yonder fane,


Where the mid-day sun through the
storied pane
Throws on the pavement a crimson
stain;
Where the banners of chivalry heavily
swing
O'er the pinnacled tomb of the Warrior
King,
With helmet and shield, and all that sort
of thing.
No!—come what may, My gentle Tray
Shan't be an intruder on bluff Harry
Tudor,
Or panoplied monarchs yet earlier and
ruder,
Whom you see on their backs, In
stone or in wax,
Though the Sacristans now are
"forbidden to ax"
For what Mister Hume calls "a
scandalous tax;"
While the Chartists insist they've a right
to go snacks.—
No!—Tray's humble tomb would look but
shabby
'Mid the sculptured shrines of that
gorgeous Abbey.
Besides, in the place They say there's
no space
To bury what wet-nurses call "a Babby."
Even "Rare Ben Jonson," that famous
wight,
I am told, is interr'd there bolt upright,
In just such a posture, beneath his bust,
As Tray used to sit in to beg for a crust.
The epitaph, too, Would scarcely do:
For what could it say, but, "Here lies
Tray,
A very good kind of a dog in his day?"
And satirical folks might be apt to
imagine it
Meant as a quiz on the House of
Plantagenet.

No! no!—The Abbey may do very well


For a feudal "Nob," or poetical "Swell,"
"Crusaders," or "Poets," or "Knights of
St. John,"
Or Knights of St. John's Wood, who once
went on
To the C a s t l e o f G o o d e L o r d e
E g l i n t o n n e.
Count Fiddle-fumkin, and Lord Fiddle-
faddle,
"Sir Craven," "Sir Gael," and "Sir
Campbell of Saddell,"
(Who, as poor Hook said, when he heard
of the feat,
"Was somehow knock'd out of his family-
seat:")
The Esquires of the body To my Lord
Tomnoddy;
"Sir Fairlie," "Sir Lamb,"
And the "Knight of the Ram,"
The "Knight of the Rose," and the
"Knight of the Dragon,"
Who, save at the flagon, And prog in
the wagon,
The newspapers tell us did little "to brag
on;"

And more, though the Muse knows but


little concerning 'em,
"Sir Hopkins," "Sir Popkins," "Sir Gage,"
and "Sir Jerningham,"
All Preux Chevaliers, in friendly rivalry
Who should best bring back the glory of
Chi-valry.—
—(Pray be so good, for the sake of my
song,
To pronounce here the ante-penultimate
long;
Or some hyper-critic will certainly cry,
"The word 'Chivalry' is but a 'rhyme to
the eye.'"
And I own it is clear A fastidious ear
Will be, more or less, always annoy'd
with you when you
insert any rhyme that's not perfectly
genuine.
As to pleasing the "eye," 'Tisn't worth
while to try,
Since Moore and Tom Campbell
themselves admit "Spinach"
Is perfectly antiphonetic to "Greenwich.")

But stay!—I say!
Let me pause while I may—
This digression is leading me sadly astray
From my object—A grave for my poor
dog Tray!

I would not place him beneath thy walls,


And proud o'ershadowing dome, St.
Paul's!
Though I've always consider'd Sir
Christopher Wren,
As an architect, one of the greatest of
men;
And,—talking of Epitaphs,—much I
admire his,
"Circumspice, si Monumentum requiris;"
Which an erudite Verger translated to
me,
"If you ask for his monument, Sir-come-
spy-see!—"
No!—I should not know where To
place him there;
I would not have him by surly Johnson
be;—
Or that queer-looking horse that is rolling
on Ponsonby;—
Or those ugly minxes The sister
Sphynxes,
Mix'd creatures, half lady, half lioness,
ergo,
(Denon says), the emblems of Leo and
Virgo;
On one of the backs of which singular
jumble,
Sir Ralph Abercrombie is going to
tumble,
With a thump which alone were enough
to despatch him,
If the Scotchman in front shouldn't
happen to catch him.

No! I'd not have him there,—nor nearer


the door,
Where the man and the Angel have got
Sir John Moore,[6]
And are quietly letting him down through
the floor,
By Gillespie, the one who escaped, at
Vellore,
Alone from the row;— Neither he, nor
Lord Howe
Would like to be plagued with a little
Bow-wow.
No, Tray, we must yield, And go
further a-field;
To lay you by Nelson were downright
effront'ry;—
—We'll be off from the City, and look at
the country.

It shall not be there, In that


sepulchred square,
Where folks are interr'd for the sake of
the air,
(Though, pay but the dues, they could
hardly refuse
To Tray what they grant to Thuggs, and
Hindoos,
Turks, Infidels, Heretics, Jumpers, and
Jews,)
Where the tombstones are placed In
the very best taste,
At the feet and the head Of the
elegant Dead,
And no one's received who's not "buried
in lead:"
For, there lie the bones of Deputy Jones,
Whom the widow's tears, and the
orphan's groans
Affected as much as they do the stones
His executors laid on the Deputy's bones;
Little rest, poor knave! Would Tray
have in his grave;
Since Spirits, 'tis plain, Are sent back
again,
To roam round their bodies,—the bad
ones in pain,—
Dragging after them sometimes a heavy
jack-chain;
Whenever they met, alarm'd by its
groans, his
Ghost all night long would be barking at
Jones's.

Nor shall he be laid By that cross Old


Maid,
Miss Penelope Bird,—of whom it is said
All the dogs in the parish were ever
afraid.
He must not be placed By one so
strait-laced
In her temper, her taste, and her morals,
and waist.
For, 'tis said, when she went up to
Heaven, and St. Peter,
Who happened to meet her, Came
forward to greet her,
She pursed up with scorn every vinegar
feature,
And bade him "Get out for a horrid Male
Creature!"
So, the Saint, after looking as if he could
eat her,
Not knowing, perhaps, very well how to
treat her,
And not being willing,—or able,—to beat
her,
Sent her back to her grave till her temper
grew sweeter,
With an epithet—which I decline to
repeat here.
No,—if Tray were interr'd By Penelope
Bird,
No dog would be e'er so be "whelp"'d
and be-"cur"r'd—
All the night long her cantankerous
Sprite
Would be running about in the pale
moon-light,
Chasing him round, and attempting to
lick
The ghost of poor Tray with the ghost of
a stick.

Stay!—let me see!— Ay—here it shall


be
At the root of this gnarled and time-worn
tree,
Where Tray and I Would often lie,
And watch the bright clouds as they
floated by
In the broad expanse of the clear blue
sky,
When the sun was bidding the world
good b'ye;
And the plaintive Nightingale, warbling
nigh,
Pour'd forth her mournful melody;

You might also like