Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Frontend Development with JavaFX and

Kotlin: Build State-of-the-Art Kotlin GUI


Applications Peter Späth
Visit to download the full and correct content document:
https://ebookmass.com/product/frontend-development-with-javafx-and-kotlin-build-sta
te-of-the-art-kotlin-gui-applications-peter-spath/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Beginning Kotlin: Build Applications with Better Code,


Productivity, and Performance Ted Hagos

https://ebookmass.com/product/beginning-kotlin-build-
applications-with-better-code-productivity-and-performance-ted-
hagos/

Programming Kotlin Applications: Building Mobile and


Server-Side Applications With Kotlin Brett Mclaughlin

https://ebookmass.com/product/programming-kotlin-applications-
building-mobile-and-server-side-applications-with-kotlin-brett-
mclaughlin/

Kotlin for Web Development and Kotlin Collections: A


Beginner's Odyssey in Web Development 2 Books in 1 Jp
Parker

https://ebookmass.com/product/kotlin-for-web-development-and-
kotlin-collections-a-beginners-odyssey-in-web-
development-2-books-in-1-jp-parker/

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


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

https://ebookmass.com/product/pro-spring-6-with-kotlin-an-in-
depth-guide-to-using-kotlin-apis-in-spring-framework-6-1st-
edition-peter-spath/
Pro Kotlin Web Apps from Scratch August Lilleaas

https://ebookmass.com/product/pro-kotlin-web-apps-from-scratch-
august-lilleaas/

Numerical Methods Using Kotlin: For Data Science,


Analysis, and Engineering 1st Edition Haksun Li

https://ebookmass.com/product/numerical-methods-using-kotlin-for-
data-science-analysis-and-engineering-1st-edition-haksun-li-2/

Numerical Methods Using Kotlin: For Data Science,


Analysis, and Engineering 1st Edition Haksun Li

https://ebookmass.com/product/numerical-methods-using-kotlin-for-
data-science-analysis-and-engineering-1st-edition-haksun-li/

Next-Level UI Development with PrimeNG: Master the


versatile Angular component library to build stunning
Angular applications 1st Edition Dale Nguyen

https://ebookmass.com/product/next-level-ui-development-with-
primeng-master-the-versatile-angular-component-library-to-build-
stunning-angular-applications-1st-edition-dale-nguyen/

Pro Kotlin Web Apps from Scratch: Building Production-


Ready Web Apps Without a Framework 1st Edition August
Lilleaas

https://ebookmass.com/product/pro-kotlin-web-apps-from-scratch-
building-production-ready-web-apps-without-a-framework-1st-
edition-august-lilleaas/
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 orders-ny@springer-sbm.com, 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 booktranslations@springernature.com; for reprint, paperback, or audio rights,
please e-mail bookpermissions@springernature.com.
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
Setting Up for Eclipse 5

by
package book.kotlinfx

import javafx.application.Application
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.layout.StackPane
import javafx.stage.Stage

fun main(args:Array<String>) {
Application.launch(HelloWorld::class.java, *args)
}

class HelloWorld : Application() {


override
fun start(primaryStage:Stage) {
primaryStage.title = "Hello World!"
val btn = Button().apply {
text = "Say 'Hello World'"
setOnAction { evnt ->
println("Hello World!")
}
}

val root = StackPane().apply {


children.add(btn)
}

with(primaryStage){
scene = Scene(root, 300.0, 250.0)
show()
}
}
}

Save the file. To now run the application, enter


./gradlew run (Linux)
gradlew run (Windows)

See Figure 1-1.


To first compile and build the project is not necessary—Gradle takes care of that if needed.

Setting Up for Eclipse

Note You can skip this section if you don’t use Eclipse.

Download and install a recent Eclipse IDE from www.eclipse.org/downloads/. Start Eclipse and then,
at Window → Preferences → Java → Installed JREs, register a JDK version 17 and make it the
default. See Figure 1-2.
Then, at File → New → Project. . . → Gradle → Gradle Project, create a new Gradle project. Once
asked, enter “kotlinfx” as the project’s name; see Figure 1-3.
Keep everything else at its defaults. You end up with a main and a subproject; see Figure 1-4.
The name of the subproject reads “lib.” We want to change it to a more meaningful variant.
6 1 Getting Started

Figure 1-1 JavaFX HelloWorld Running

Figure 1-2 Eclipse JRE Setting

Caution Due to a design issue inside the Gradle-Plugin for Eclipse 2022-12, you cannot rename the
subproject’s name via Mouse-Right → Refactor → Rename. . . We must apply a workaround.
Setting Up for Eclipse 7

Figure 1-3 Eclipse Gradle Project Wizard

First, edit file settings.gradle. Change the line


include('lib')
->
include('HelloWorld')

Now delete the “lib” subproject from Eclipse. Make sure the “Also delete project contents” checkbox
is not checked.
In your system’s file explorer, rename folder lib inside WORKSPACE/kotlinfx to
HelloWorld.
On the main project, invoke Mouse-Right → Configure → Configure and Detect Nested
Projects. . . Press the “Finish” button. Ignore possibly shown errors.
Just to be on the safe side, restart Eclipse. The package view should now be as shown in
Figure 1-5.
Back to the application, replace the contents of the build.gradle file by
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.7.10'
id 'application'
id 'org.openjfx.javafxplugin' version '0.0.13'
}

repositories {
mavenCentral()
8 1 Getting Started

dependencies {
}

application {
mainClass = 'book.kotlinfx.AppKt'
}

compileKotlin {
kotlinOptions {
suppressWarnings = true
jvmTarget = "17"
}
}

javafx {
version = "19"
modules("javafx.controls", "javafx.graphics")
}

After changes to file build.gradle, the project regularly needs to be updated: on “kotlinfx,”
press Mouse-Right → Gradle → Refresh Gradle Project. Also, remove the packages inside src/
test/java; we don’t need them for now.

Figure 1-4 Eclipse


Gradle Project
Setting Up for Eclipse 9

A fresh Eclipse installation doesn’t know how to handle Kotlin files. To fix this, open Help →
Eclipse Marketplace. . . Enter “kotlin” in the search field, and select to install “Kotlin Plugin for
Eclipse” from the search result list. Restart Eclipse twice.
Make a new folder src/main/kotlin and register it as a source folder via Mouse-Right →
Java Build Path → Source → Add folder. . . See Figure 1-6.

Figure 1-5 Eclipse Subproject Renamed

Figure 1-6 Eclipse Kotlin Sources


Another random document with
no related content on Scribd:
detailed many things regarding the wild flight of himself and
Aguinaldo's party up the coast. The last words written in it
were pathetic and indicated something of the noble character
of the man. The passage, which was written only a few minutes
previously, while the fight was on and while death even then
was before him, said: 'I am holding a difficult position
against desperate odds, but I will gladly die for my beloved
country.'

"Pilar alive and in command, shooting down good Americans, was


one thing, but Pilar lying in that silent mountain trail, his
body half denuded of its clothes, and his young, handsome,
boyish face discolored with the blood which saturated his
blouse and stained the earth, was another thing. We could not
help but feel admiration for his gallant fight, and sorrow for
the sweetheart whom he left behind. The diary was dedicated to
the girl, and I have since learned that he was to have married
her in Dagupan about two weeks before. But the Americans came
too soon. Instead of wedding bells there sounded the bugle
calls of the foe and he was hurriedly ordered to accompany his
chief, Aguinaldo, on that hasty retreat to the mountains. The
marriage was postponed, and he carried out his orders by
leaving for the north. Pilar was one of the best types of the
Filipino soldier. He was only 23 years old, but he had been
through the whole campaign in his capacity as
brigadier-general. It was he who commanded the forces at
Quingua the day that Colonel Stotsenberg was killed, and it
may be remembered that the engagement that day was one of the
most bloody and desperate that has occurred on the island. He
was a handsome boy, and was known as one of the Filipinos who
were actuated by honestly patriotic motives, and who fought
because they believed they were fighting in the right and not
for personal gain or ambition."

Chicago Record's Stories of Filipino Warfare,


page 14.
PHILIPPINE ISLANDS: A. D. 1899 (March-July).
The establishment of a provisional government
in the island of Negros.

Negros "was the first island to accept American sovereignty.


Its people unreservedly proclaimed allegiance to the United
States and adopted a constitution looking to the establishment
of a popular government. It was impossible to guarantee to the
people of Negros that the constitution so adopted should be
the ultimate form of government. Such a question, under the
treaty with Spain and in accordance with our own Constitution
and laws, came exclusively within the jurisdiction of the
Congress. The government actually set up by the inhabitants of
Negros eventually proved unsatisfactory to the natives
themselves. A new system was put into force by order of the
Major-General Commanding the Department [July 22, 1899], of
which the following are the most important elements:

"It was ordered that the government of the island of Negros


should consist of a military governor appointed by the United
States military governor of the Philippines, and a civil
governor and an advisory council elected by the people. The
military governor was authorized to appoint secretaries of the
treasury, interior, agriculture, public instruction, an
attorney-general, and an auditor. The seat of government was
fixed at Bacolod. The military governor exercises the supreme
executive power. He is to see that the laws are executed,
appoint to office, and fill all vacancies in office not
otherwise provided for, and may with the approval of the
military governor of the Philippines, remove any officer from
office. The civil governor advises the military governor on
all public civil questions and presides over the advisory
council. He, in general, performs the duties which are
performed by secretaries of state in our own system of
government. The advisory council consists of eight members
elected by the people within territorial limits which are
defined in the order of the commanding general. The times and
places of holding elections are to be fixed by the military
governor of the island of Negros. The qualifications of voters
are as follows:

(1) A voter must be a male citizen of the island of Negros.

(2) Of the age of 21 years.

(3) He shall be able to speak, read, and write the English,


Spanish, or Visayan language, or he must own real property
worth $500, or pay a rental on real property of the value of
$1,000.

(4) He must have resided in the island not less than one year
preceding, and in the district in which he offers to register
as a voter not less than three months immediately preceding
the time he offers to register.

(5) He must register at a time fixed by law before voting.

(6) Prior to such registration he shall have paid all taxes


due by him to the Government.

{384}

Provided, that no insane person shall bc allowed to register


or vote. The military governor has the right to veto all bills
or resolutions adopted by the advisory council, and his veto
is final if not disapproved by the military governor of the
Philippines. The advisory council discharges all the ordinary
duties of a legislature. The usual duties pertaining to said
offices are to be performed by the secretaries of the
treasury, interior, agriculture, public instruction, the
attorney-general, and the auditor. The judicial power is
vested in three judges, who are to be appointed by the
military governor of the island. Inferior courts are to be
established. Free public schools are to be established
throughout the populous districts of the island, in which the
English language shall be taught, and this subject will
receive the careful consideration of the advisory council. The
burden of government must be distributed equally and equitably
among the people. The military authorities will collect and
receive the customs revenue, and will control postal matters
and Philippine inter-island trade and commerce. The military
governor, subject to the approval of the military governor of
the Philippines, determines all questions not specifically
provided for and which do not come under the jurisdiction of
the advisory council."

Message of the President, December 5, 1899


(Message and Documents: Abridgment, 1899-1900,
volume 2, page 47).

Also in:
Report of General Otis (Message and Documents,
volume 2, page 1131-1137).

PHILIPPINE ISLANDS: A. D. 1899 (May-August).


Agreement of terms with the Sultan of Jolo concerning
the Sulu Archipelago.

On the 19th of May, a detachment of U. 8. troops took the


place of the Spanish garrison at Jolo, the military station in
the Sulu Archipelago. On the 3d of July, General Otis, Military
Governor of the Philippines, issued orders as follows to
General J. C. Bates, U. S. V.: "You will proceed as soon as
practicable to the United States military station of Jolo, on
the island of that name, and there place yourself in
communication with the Sultan of Jolo, who is believed to be
at Siassi, where he was sojourning when the last information
concerning him was received. You are hereby appointed and
constituted an agent on the part of the United States military
authorities in the Philippines to discuss, enter into
negotiations, and perfect, if possible, a written agreement of
character and scope as hereinafter explained, with the Sultan,
which upon approval at these headquarters and confirmation by
the supreme executive authority of the United States, will
prescribe and control the future relations, social and
political, between the United States Government and the
inhabitants of the archipelago. … In your discussions with the
Sultan and his datos the question of sovereignty will be
forced to the front, and they will undoubtedly request an
expression of opinion thereon, as they seem to be impressed
apparently with the belief that the recent Spanish authorities
with whom they were in relationship have transferred full
sovereignty of the islands to them. The question is one which
admits of easy solution, legally considered, since by the
terms of treaties or protocols between Spain and European
powers Spanish sovereignty over the archipelago is conceded.
Under the agreement between Spain and the Sultan and datos of
July, 1878, the latter acknowledged Spanish sovereignty in the
entire archipelago of Jolo and agreed to become loyal Spanish
subjects, receiving in consideration certain specific payments
in money. The sovereignty of Spain, thus established and
acknowledged by all parties in interest, was transferred to
the United States by the Paris treaty. The United States has
succeeded to all the rights which Spain held in the
archipelago, and its sovereignty over the same is an
established fact. But the inquiry arises as to the extent to
which that sovereignty can be applied under the agreement of
1878 with the Moros. Sovereignty, of course, implies full
power of political control, but it is not incompatible with
concessionary grants between sovereign and subject. The Moros
acknowledged through their accepted chiefs Spanish sovereignty
and their subjection thereto, and that nation in turn conferred
upon their chiefs certain powers of supervision over them and
their affairs. The kingly prerogatives of Spain, thus abridged
by solemn concession, have descended to the United States, and
conditions existing at the time of transfer should remain. The
Moros are entitled to enjoy the identical privileges which
they possessed at the time of transfer, and to continue to
enjoy them until abridged or modified by future mutual
agreement between them and the United States, to which they
owe loyalty, unless it becomes necessary to invoke the
exercise of the supreme powers of sovereignty to meet
emergencies. You will therefore acquaint yourself thoroughly
with the terms of the agreement of 1878, and take them as a
basis for your directed negotiations. …

"It is greatly desired by the United States for the sake of


the individual improvement and social advancement of the
Moros, and for the development of the trade and agriculture of
the islands in their interests, also for the welfare of both the
United States and Moros, that mutual friendly and well-defined
relations be established. If the Sultan can be made to give
credit to and fully understand the intentions of the United
States, the desired result can be accomplished. The United
States will accept the obligations of Spain under the
agreement of 1878 in the matter of money annuities, and in
proof of sincerity you will offer as a present to the Sultan
and datos $10,000, Mexican, with which you will be supplied
before leaving for Jolo—the same to be handed over to them,
respectively, in amounts agreeing with the ratio of payments
made to them by the Spanish Government for their declared
services. From the 1st of September next, and thereafter, the
United States will pay to them regularly the sums promised by
Spain in its agreement of 1878, and in any subsequent promises
of which proof can be furnished. The United States will
promise, in return for the concessions to be hereinafter
mentioned, not to interfere with, but to protect the Moros in
the free exercise of their religion and customs, social and
domestic, and will respect the rights and dignities of the
Sultan and his advisers."

{385}

Of the results of the mission of General Bates, General Otis


reported subsequently as follows:

"General Bates had a difficult task to perform and executed it


with tact and ability. While a number of the principal datos were
favorably inclined, the Sultan, not responding to invitations,
kept aloof and was represented by his secretary, until
finally, the general appearing at Maibung, the Moro capital, a
personal interview was secured. He being also Sultan of North
Borneo and receiving large annual payments from the North
Borneo Trading Company, expected like returns from the United
States, and seemed more anxious to obtain personal revenue
than benefits for his people. Securing the port of Siassi from
the Spaniards, establishing there his guards and police, he
had received customs revenues from the Sandaken trade which he
was loath to surrender. Negotiations continued well into
August, and finally, after long conferences, an agreement was
reached by which the United States secured much more liberal
terms than the Spaniards were ever able to obtain."

Report of General Otis, August 31, 1899


(Message and Documents: Abridgment, 1899-1900,
volume 2, pages 1162-1164).

"By Article I the sovereignty of the United States over the


whole archipelago of Jolo and its dependencies is declared and
acknowledged. The United States flag will be used in the
archipelago and its dependencies, on land and sea. Piracy is
to be suppressed, and the Sultan agrees to co-operate heartily
with the United States authorities to that end and to make
every possible effort to arrest and bring to justice all
persons engaged in piracy. All trade in domestic products of
the archipelago of Jolo when carried on with any part of the
Philippine Islands and under the American flag shall be free,
unlimited, and undutiable. The United States will give full
protection to the Sultan in case any foreign nation should
attempt to impose upon him. The United States will not sell
the island of Jolo or any other island of the Jolo archipelago
to any foreign nation without the consent of the Sultan.
Salaries for the Sultan find his associates in the
administration of the islands have been agreed upon to the
amount of $760 monthly. Article X provides that any slave in
the archipelago of Jolo shall have the right to purchase
freedom by paying to the master the usual market value. The
agreement by General Bates was made subject to confirmation by
the President and to future modifications by the consent of
the parties in interest. I have confirmed said agreement,
subject to the action of the Congress, and with the
reservation, which I have directed shall be communicated to
the Sultan of Jolo, that this agreement is not to be deemed in
any way to authorize or give the consent of the United States
to the existence of slavery in the Sulu archipelago."

Message of the President, December 5, 1899


(Message and Documents: Abridgment, 1899-1900,
volume 2, pages 47-48).

"The population of the Sulu Archipelago is reckoned at


120,000, mostly domiciled in the island of Jolo, and numbers
20,000 fighting men. Hostilities would be unfortunate for all
parties concerned, would be very expensive to the United
States in men and money, and destructive of any advancement of
the Moros for years to come. Spain's long struggle with these
people and their dislike for the former dominant race in the
Philippines, inherited, it would seem, by each rising
generation during three centuries, furnishes an instructive
lesson. Under the pending agreement General Bates, assisted by
the officers of the Navy, quietly placed garrisons of one
company each at Siassi and at Bongao, on the Tawai Tawai group
of islands, where they were well received by the friendly
natives. With the approval of the agreement, the only
difficulty to a satisfactory settlement of the Sulu affairs
will arise from discontent on the part of the Sultan
personally because of a supposed decrease in anticipated
revenues or the machinations of the insurgents of Mindanao,
who are endeavoring to create a feeling of distrust and
hostility among the natives against the United States troops.

"The Sultan's government is one of perfect despotism, in form


at least, as all political power is supposed to center in his
person; but this does not prevent frequent outbreaks on the
part of the datos, who frequently revolt, and are now, in two
or three instances, in declared enmity. All Moros, however,
profess the Mohammedan religion, introduced in the fourteenth
century, and the sacredness of the person of the Sultan is
therefore a tenet of faith. This fact would prevent any marked
success by a dato in attempting to secure supreme power. Spain
endeavored to supplant the Sultan with one of his most
enterprising chiefs and signally failed. Peonage or a species
of serfdom enters largely into the social and domestic
arrangements and a dato's following or clan submits itself
without protest to his arbitrary will. The Moro political
fabric bears resemblance to the state of feudal times—the
Sultan exercising supreme power by divine right, and his
datos, like the feudal lords, supporting or opposing him at
will, and by force of arms occasionally, but not to the extent
of dethronement, as that would be too great a sacrilege for a
Mohammedan people to seek to consummate. The United States
must accept these people as they are, and endeavor to
ameliorate their condition by degrees, and the best means to
insure success appears to be through the cultivation of
friendly sentiments and the introduction of trade and commerce
upon approved business methods. To undertake forcible radical
action for the amelioration of conditions or to so interfere
with their domestic relations as to arouse their suspicions
and distrust would be attended with unfortunate consequences."

Report of General Otis, August 31, 1899


(Message and Documents: Abridgment, 1899-1900,
volume 2, page 1165).

PHILIPPINE ISLANDS: A. D. 1899-1900.


Military operations against the Insurgents.
Death of General Lawton.

"The enlargement of the field of operations and government in


the Philippine Islands made it impracticable to conduct the
business under the charge of the army in those islands through
the machinery of a single department, and by order made April
7, 1900, the Philippine Islands were made a military division,
consisting of four departments: The Department of Northern Luzon,
the Department of Southern Luzon, the Department of the
Visayas, and the Department of Mindanao and Jolo. The
Department of Northern Luzon is subdivided into six, the
Department of Southern Luzon into four, the Department of the
Visayas into four, and the Department of Mindanao and Jolo
into four military districts. …

"At the date of the last report (November 29, 1899 [see
above]) the government established by the Philippine
insurgents in central Luzon and the organized armed forces by
which it was maintained had been destroyed, and the principal
civil and military leaders of the insurrection, accompanied by
small and scattered bands of troops, were the objects of
pursuit in the western and the northern parts of the island.
{386}
That pursuit was prosecuted with vigor and success, under
conditions of extraordinary difficulty and hardship, and
resulted in the further and practically complete
disintegration of the insurrectionary bands in those regions,
in the rescue of nearly all the American prisoners and the
greater part of the Spanish prisoners held by the insurgents,
in the capture of many of the leading insurgents, and in the
capture and destruction of large quantities of arms,
ammunition, and supplies. There still remained a large force
of insurgents in Cavite and the adjacent provinces south of
Manila, and a considerable force to the east of the Rio Grande
de Pampanga, chiefly in the province of Bulacan, while in the
extreme southeastern portions of Luzon, and in the various
Visayan islands, except the island of Negros, armed bodies of
Tagalogs had taken possession of the principal seacoast towns,
and were exercising military control over the peaceful
inhabitants. Between the insurgent troops in Bulacan and the
mountains to the north, and the insurgents in the south,
communication was maintained by road and trail, running along
and near the eastern bank of the Mariquina River, and through
the towns of Mariquina, San Mateo, and Montalban and the
province of Morong. This line of communication, passing
through rough and easily defended country, was strongly
fortified and held by numerous bodies of insurgents.

"On the 18th of December, 1899, a column, under the command of


Major General Henry W. Lawton, proceeded from Manila, and
between that date and the 29th of December captured all the
fortified posts of the insurgents, took possession of the line
of communication, which has ever since been maintained, and
destroyed, captured, or dispersed the insurgent force in that
part of the island. In the course of this movement was
sustained the irremediable loss of General Lawton, who was
shot and instantly killed while too fearlessly exposing his
person in supervising the passing of his troops over the river
Mariquina at San Mateo.

"On the 4th of January, 1900, General J. C. Bates, U. S. V.,


was assigned to the command of the First Division of the
Eighth Army Corps, and an active campaign under his direction
was commenced in Southern Luzon. The plan adopted was to
confront and hold the strong force of the enemy near Imus and
to the west of Bacoor by a body of troops under General
Wheaton, while a column, under General Schwan, should move
rapidly down the west shore of the Laguna de Bay to Biñang,
thence turn southwesterly and seize the Silang, Indang, and
Naic road, capture the enemy's supplies supposed to be at the
towns of Silang and Indang, and arrest the retreat of the
enemy, when he should be driven from northern Cavite by our
troops designated to attack him there, and thus prevent his
reassembling in the mountains of southern Cavite and northern
Batangas. This plan was successfully executed. General
Schwan's column moved over the lines indicated with great
rapidity, marching a distance of over 600 miles, striking and
defeating numerous bodies of insurgents and capturing many
intrenched positions, taking possession of and garrisoning
towns along the line, and scattering and demoralizing all the
organized forces of the enemy within that section of country.
From these operations and the simultaneous attacks by our
troops under General Wheaton in the north the rebel forces in
the Cavite region practically disappeared, the members either
being killed or captured or returning to their homes as
unarmed citizens, and a few scattered parties escaping through
General Schwan's line to the south. By the 8th of February the
organized forces of the insurgents in the region mentioned had
ceased to exist. In large portions of the country the
inhabitants were returning to their homes and resuming their
industries, and active trade with Manila was resumed. In the
course of these operations about 600 Spanish prisoners were
released from the insurgents, leaving about 600 more still in
their hands in the extreme southeastern provinces of Camarines
and Albay, nearly all of whom were afterwards liberated by our
troops. In the meantime an expedition was organized under the
command of Brigadier General William A. Kobbé, U. S. V., to
expel the Tagalogs who had taken possession of the principal
hemp ports of the islands situated in Albay, the extreme
southeastern province of Luzon, and in the islands of Leyte,
Samar, and Catanduanes. This expedition sailed from Manila on
the 18th of January and accomplished its object. All of the
principal hemp ports were relieved from control of the
insurgents, garrisoned by American troops, and opened to
commerce by order of the military governor of the islands on
the 30th of January and the 10th and 14th of February. The
expedition met with strong resistance at Legaspi by an
intrenched force under the Chinese general, Paua. He was
speedily overcome and went into the interior. After a few days
he reassembled his forces and threatened the garrisons which
had been left in Albay and Legaspi, whereupon he was attacked,
and defeated, and surrendered. Thirty pieces of artillery, a
large quantity of ammunition, a good many rifles, and a
considerable amount of money were captured by this expedition.

"On the 15th of February an expedition, under the supervision


of Major-General Bates and under the immediate command of
Brigadier General James M. Bell, U. S. V., sailed from Manila
to take possession of the North and South Camarines provinces
and Western Albay, in which the insurgent forces had been
swelled by the individuals and scattered bands escaping from
our operations in various sections of the north. The insurgent
force was defeated after a sharp engagement near the mouth of
the Bicol River, pursued, and scattered. Large amounts of
artillery and war material were captured. The normal
conditions of industry and trade relations with Manila were
resumed by the inhabitants. On the 20th of March the region
covered by the last-described operations was created a
district of southeastern Luzon, under the command of General
James M. Bell, who was instructed to proceed to the
establishment of the necessary customs and internal-revenue
service in the district. In the meantime similar expeditions
were successfully made through the mountains of the various
islands of the Visayan Group, striking and scattering and
severely punishing the bands of bandits and insurgents who
infested those islands. In the latter part of March General
Bates proceeded with the Fortieth infantry to establish
garrisons in Mindanao. The only resistance was of a trifling
character at Cagayan, the insurgent general in northeastern
Mindanao surrendering and turning over the ordnance in his
possession.
{387}
With [the execution of these movements] all formal and open
resistance to American authority in the Philippines
terminated, leaving only an exceedingly vexatious and annoying
guerilla warfare of a character closely approaching
brigandage, which will require time, patience, and good
judgment to finally suppress. As rapidly as we have occupied
territory, the policy of inviting inhabitants to return to
their peaceful vocations, and aiding them in the
reestablishment of their local governments, has been followed,
and the protection of the United States has been promised to
them. The giving of this protection has led to the
distribution of troops in the Philippine Islands to over 400
different posts, with the consequent labor of administration
and supply. The maintenance of these posts involves the
continued employment of a large force, but as the Tagalogs who
are in rebellion have deliberately adopted the policy of
murdering, so far as they are able, all of their countrymen
who are friendly to the United States, the maintenance of
garrisons is at present necessary to the protection of the
peaceful and unarmed Filipinos who have submitted to our
authority; and if we are to discharge our obligations in that
regard their reduction must necessarily be gradual."

United States, Secretary of War,


Annual Report, November 30, 1900, pages 5-10.

PHILIPPINE ISLANDS: A. D. 1900 (January).


Report of the First Philippine Commission.

The First Commission to the Philippines returned to the United


States in the autumn of 1899, and then submitted to the President
a brief preliminary statement of its proceedings in the
Islands and the opinions its members had formed, concerning
the spirit and extent of the Tagalo revolt, the general
disposition of the people at large, their capacity for
independent self-government, etc. On the 31st of January
following the commissioners presented a report which deals
extensively with many subjects of investigation and
deliberation. In Part I., it sets forth the efforts made by
the commission "toward conciliation and the establishment of
peace," through interviews with various emissaries of
Aguinaldo, and others, and by means of a proclamation to the
people. In Part II., it gives an extended account of the races
and tribes of which the native population of the Islands is
composed. In Part III., it details the provision that has
heretofore been made for education, and states the conclusions
of the commission as to the capacity of the people and their
fitness for a popular government. In Part IV., a very full
account of the Spanish organization of government in the
Philippines, general, provincial and municipal, is given, and
the reforms that were desired by the Filipino people are
ascertained. From this the commission proceeds to consider the
question of a plan of government for the Islands under the
sovereignty of the United States, and concludes that the
Territorial system of the United States offers all that can be
desired. "What Jefferson and the nation did for Louisiana,"
says the report, "we are … free to-day to do for the
Philippines. The fact that Bonaparte had provided in the
treaty that Louisiana should in due time be admitted as a
State in the Union, and that in the meantime its inhabitants
should have protection in the free enjoyment of their liberty,
property, and religion, made no difference in the relation of
Louisiana to the Constitution of the United States so long as
Louisiana remained a Territory; and, if it had made a
difference, it should have constituted something of a claim to
the immediate enjoyment of some or all of the benefits of the
Constitution. Unmoved by that consideration, however, the
Jeffersonian policy established once for all the subjection of
national domain outside the States to the absolute and
unrestricted power of Congress. The commission recommends that
in dealing with the Philippines this vast power be exercised
along the lines laid down by Jefferson and Madison in
establishing a government for Louisiana, but with … deviations
in the direction of larger liberty to the Filipinos. … The
result would be substantially the transformation of their
second-class Territorial government of Louisiana into a
Territorial government of the first-class for the Philippine
Islands." To this recommendation of the Territorial system of
government the commission adds a strenuous plea for a closely
guarded civil service. "It is a safe and desirable rule," says
the report, "that no American should be appointed to any office
in the Philippines for which a reasonably qualified Filipino
can, by any possibility, be secured. Of course the merit or
business system must be adopted and lived up to; the patronage
or spoils system would prove absolutely fatal to good
government in this new Oriental territory." Further parts of
the report are devoted to the Philippine judicial system, as
it had been and as it should be; to "the condition and needs
of the United States in the Philippines from a naval and
maritime standpoint"; to the secular clergy and religious
orders; to registration laws; to the currency; to the Chinese
in the Philippines; and to public health. Among the exhibits
appended in volume 1 of the published Report are the
constitution of Aguinaldo's Philippine Republic (called the
Malolos constitution), and several other constitutional drafts
and proposals from Filipino sources, indicating the political
ideas that prevail.

Report of the Philippine Commission,


January 31, 1900, volume 1.

See, also (in this volume),


EDUCATION: A. D. 1898 (PHILIPPINE ISLANDS).

PHILIPPINE ISLANDS: A. D. 1900 (March).


Institution of municipal governments.

By General Orders, on the 29th of March, 1900, the Military


Governor of the Islands promulgated a law providing for the
election and institution of municipal governments, the
provisions of which law had been framed by a board appointed
in the previous January, under the presidency of Don Cayetano
Arellano, chief justice of the Philippines. The first chapter
of the law reads as follows:

"ARTICLE 1.
The towns of the Philippine Islands shall be recognized as
municipal corporations with the same limits as heretofore
established, upon reorganizing under the provisions of this
order. All property vested in any town under its former
organization shall be vested in the same town upon becoming
incorporated hereunder.

"ARTICLE 2.
Towns so incorporated shall be designated as 'municipios,' and
shall be known respectively by the names heretofore adopted.
Under such names they may, without further authorization, sue
and be sued, contract and be contracted with, acquire and hold
real and personal property for the general interests of the
town, and exercise all the powers hereinafter conferred. The
city of Manila is exempt from the provisions of this order.

{388}

"ARTICLE 3.
The municipal government of each town is hereby vested in an
alcalde and a municipal council. The alcalde and councilors,
together with the municipal lieutenant, shall be chosen at
large by the qualified electors of the town, and their term of
office shall be for two years from and after the first Monday
in January next after their election and until their
successors are duly chosen and qualified: Provided, That the
alcalde and municipal lieutenant elected in 1900 shall hold
office until the first Monday in January, 1902, only; and that
the councilors elected in 1900 shall divide themselves, by
lot, into two classes; the scats of those of the first class
shall be vacated on the first Monday of January, 1901, and
those of the second class one year thereafter, so that
one-half of the municipal council shall be chosen annually.

"ARTICLE 4.
Incorporated towns shall be of four classes, according to the
number of inhabitants. Towns of the first class shall be those
which contain not less than 25,000 inhabitants and shall have
18 councilors; of the second class, those containing 18,000
and less than 25,000 inhabitants and shall have 14 councilors;
of the third class, those containing 10,000 and less than
18,000 inhabitants and shall have 10 councilors; of the fourth
class, those containing less than 10,000 inhabitants and shall
have 8 councilors. Towns of less than 2,000 inhabitants may
incorporate under the provisions of this order, or may, upon
petition to the provincial governor, signed by a majority of
the qualified electors thereof, be attached as a barrio to an
adjacent and incorporated town, if the council of the latter
consents.

The qualifications of voters are defined in the second chapter


as follows:

"ARTICLE 5.
The electors charged with the duty of choosing elective
municipal officers must be male persons, 23 years of age or
over, who have had a legal residence in the town in which they
exercise the suffrage for a period of six months immediately
preceding the election, and who are not citizens or subjects
of any foreign power, and who are comprised within one of the
following three classes:

1. Those who, prior to the 13th of August, 1898, held the


office of municipal captain, gobernadorcillo, lieutenant or
cabeza de barangay.

2. Those who annually pay 30 pesos or more of the established


taxes.

3. Those who speak, read, and write English or Spanish."

Succeeding articles in this chapter prescribe the oath to be


taken and subscribed by each elector before his ballot is
cast, recognizing and accepting "the supreme authority of the
United States of America"; appoint the times and places for
holding elections, and set forth the forms to be observed in
them. In the third chapter, the qualifications of officers are
thus defined:

"ARTICLE 13.
An alcalde, municipal lieutenant, or councilor must have the
following qualifications:

1. He must be a duly qualified elector of the municipality in


which he is a candidate, of 26 years of age or over, and have
had a legal residence therein for at least one year prior to
the date of election.

2. He must correctly speak, read, and write either the English


language or the local dialect.

"ARTICLE 14.
In no case can there be elected or appointed to municipal
office ecclesiastics, soldiers in active service, persons
receiving salary from municipal, provincial or government
funds; debtors to said funds, whatever the class of said
funds; contractors of public works and their bondsmen; clerks
and functionaries of the administration or government while in
said capacity; bankrupts until discharged, or insane or
feeble-minded persons.

"ARTICLE 15.
Each and every person elected or appointed to a municipal
office under the provisions of this order shall, before
entering upon the duties thereof, take and subscribe before
the alcalde or town secretary"—an oath analogous to that
required from the electors.

Further articles in this chapter and the next define the


duties of the alcalde, the municipal lieutenant, municipal
attorney, municipal secretary, municipal treasurer, and the
municipal councilors. The fifth chapter relates to taxation
and finances; the sixth and seventh contain provisions as
follows:

"ARTICLE 53.
The governor of the province shall be ex officio president of
all municipal councils within the province and shall have
general supervisory charge of the municipal affairs of the
several towns and cities therein organized under the
provisions of this order, and in his said supervisory capacity
may inspect or cause to be inspected, at such times as he may
determine, the administration of municipal affairs and each
and every department thereof, and may hear and determine all
appeals against the acts of municipal corporations or their
officers. He, or those whom he may designate in writing for
that duty, shall at all times have free access to all records,
books, papers, moneys, and property of the several towns and
cities of the province, and may call upon the officers thereof
for an accounting of the receipts and expenditures, or for a
general or special report of the official acts of the several
municipal councils or of any and every of them, or of any and
every of the officers thereof, at any time, and as often as he
may consider necessary to inform himself of the state of the
finances or of the administration of municipal affairs, and
such requests when made must be complied with without excuse,
pretext, or delay. He may suspend or remove municipal
officers, either individually or collectively, for cause, and
appoint substitutes therefor permanently, for the time being
or pending the next general election, or may call a special
election to fill the vacancy or vacancies caused by such
suspension or removal, reporting the cause thereof with a full
statement of his action in the premises to the governor of the
islands without delay. He shall forward all questions or
disputes that may arise over the boundaries or jurisdictional
limits of the city, towns, or municipalities to the governor
of the islands for final determination, together with full
report and recommendations relative to the same. He may, with

You might also like