Many types of components, such as tabs, menus, image galleries, and so on, need the content to render.
Just like built-in browser <select>
expects <option>
items, our <custom-tabs>
may expect the actual tab content to be passed. And a <custom-menu>
may expect menu items.
The code that makes use of <custom-menu>
can look like this:
…Then our component should render it properly, as a nice menu with given title and items, handle menu events, etc.
How to implement it?
After learning a bit of Android Java I've chosen to make a tiny game so that I can use the learned techniques in a real app. I had the idea of a slot machine simulator: You press a button and it generates three random numbers. The sum of the random numbers becomes your final result and a sound is played. Depending on the result a message is. Casinos are a shady business, but I'm even more suspicious of a slot machine that offers me a random prize without displaying the result of the spin. Infrastructure I don't recommend developing a habit of relying on non-standard libraries that don't do very much. Assignment: Java Game: Student: Matt McKenzie: Date: November 14, 2011: Description: For my Java final project we were asked to make a game using the applet and Java theory we have covered: so far. For my game i decided to do a slot machine. I chose this idea because I have always had a fascination with.
We could try to analyze the element content and dynamically copy-rearrange DOM nodes. That’s possible, but if we’re moving elements to shadow DOM, then CSS styles from the document do not apply in there, so the visual styling may be lost. Also that requires some coding.
Luckily, we don’t have to. Shadow DOM supports <slot>
elements, that are automatically filled by the content from light DOM.
Named slots
Let’s see how slots work on a simple example.
Here, <user-card>
shadow DOM provides two slots, filled from light DOM:
In the shadow DOM, <slot name='X'>
defines an “insertion point”, a place where elements with slot='X'
are rendered.
Then the browser performs “composition”: it takes elements from the light DOM and renders them in corresponding slots of the shadow DOM. At the end, we have exactly what we want – a component that can be filled with data.
Here’s the DOM structure after the script, not taking composition into account:
We created the shadow DOM, so here it is, under #shadow-root
. Now the element has both light and shadow DOM.
For rendering purposes, for each <slot name='...'>
in shadow DOM, the browser looks for slot='...'
with the same name in the light DOM. These elements are rendered inside the slots:
The result is called “flattened” DOM:
…But the flattened DOM exists only for rendering and event-handling purposes. It’s kind of “virtual”. That’s how things are shown. But the nodes in the document are actually not moved around!
That can be easily checked if we run querySelectorAll
: nodes are still at their places.
So, the flattened DOM is derived from shadow DOM by inserting slots. The browser renders it and uses for style inheritance, event propagation (more about that later). But JavaScript still sees the document “as is”, before flattening.
The slot='...'
attribute is only valid for direct children of the shadow host (in our example, <user-card>
element). For nested elements it’s ignored.
For example, the second <span>
here is ignored (as it’s not a top-level child of <user-card>
):
If there are multiple elements in light DOM with the same slot name, they are appended into the slot, one after another.
For example, this:
Gives this flattened DOM with two elements in <slot name='username'>
:
Slot fallback content
If we put something inside a <slot>
, it becomes the fallback, “default” content. The browser shows it if there’s no corresponding filler in light DOM.
For example, in this piece of shadow DOM, Anonymous
renders if there’s no slot='username'
in light DOM.
Default slot: first unnamed
The first <slot>
in shadow DOM that doesn’t have a name is a “default” slot. It gets all nodes from the light DOM that aren’t slotted elsewhere.
For example, let’s add the default slot to our <user-card>
that shows all unslotted information about the user:
All the unslotted light DOM content gets into the “Other information” fieldset.
Elements are appended to a slot one after another, so both unslotted pieces of information are in the default slot together.
The flattened DOM looks like this:
Menu example
Now let’s back to <custom-menu>
, mentioned at the beginning of the chapter.
We can use slots to distribute elements.
Here’s the markup for <custom-menu>
:
The shadow DOM template with proper slots:
<span slot='title'>
goes into<slot name='title'>
.- There are many
<li slot='item'>
in the template, but only one<slot name='item'>
in the template. So all such<li slot='item'>
are appended to<slot name='item'>
one after another, thus forming the list.
The flattened DOM becomes:
One might notice that, in a valid DOM, <li>
must be a direct child of <ul>
. But that’s flattened DOM, it describes how the component is rendered, such thing happens naturally here.
We just need to add a click
handler to open/close the list, and the <custom-menu>
is ready:
Here’s the full demo:
Of course, we can add more functionality to it: events, methods and so on.
Updating slots
What if the outer code wants to add/remove menu items dynamically?
The browser monitors slots and updates the rendering if slotted elements are added/removed.
Also, as light DOM nodes are not copied, but just rendered in slots, the changes inside them immediately become visible.
So we don’t have to do anything to update rendering. But if the component code wants to know about slot changes, then slotchange
event is available.
For example, here the menu item is inserted dynamically after 1 second, and the title changes after 2 seconds:
The menu rendering updates each time without our intervention.
There are two slotchange
events here:
At initialization:
slotchange: title
triggers immediately, as theslot='title'
from the light DOM gets into the corresponding slot.After 1 second:
slotchange: item
triggers, when a new<li slot='item'>
is added.
Please note: there’s no slotchange
event after 2 seconds, when the content of slot='title'
is modified. That’s because there’s no slot change. We modify the content inside the slotted element, that’s another thing.
If we’d like to track internal modifications of light DOM from JavaScript, that’s also possible using a more generic mechanism: MutationObserver.
Slot API
Finally, let’s mention the slot-related JavaScript methods.
As we’ve seen before, JavaScript looks at the “real” DOM, without flattening. But, if the shadow tree has {mode: 'open'}
, then we can figure out which elements assigned to a slot and, vise-versa, the slot by the element inside it:
node.assignedSlot
– returns the<slot>
element that thenode
is assigned to.slot.assignedNodes({flatten: true/false})
– DOM nodes, assigned to the slot. Theflatten
option isfalse
by default. If explicitly set totrue
, then it looks more deeply into the flattened DOM, returning nested slots in case of nested components and the fallback content if no node assigned.slot.assignedElements({flatten: true/false})
– DOM elements, assigned to the slot (same as above, but only element nodes).
These methods are useful when we need not just show the slotted content, but also track it in JavaScript.
For example, if <custom-menu>
component wants to know, what it shows, then it could track slotchange
and get the items from slot.assignedElements
:
Summary
Usually, if an element has shadow DOM, then its light DOM is not displayed. Slots allow to show elements from light DOM in specified places of shadow DOM.
There are two kinds of slots:
- Named slots:
<slot name='X'>...</slot>
– gets light children withslot='X'
. - Default slot: the first
<slot>
without a name (subsequent unnamed slots are ignored) – gets unslotted light children. - If there are many elements for the same slot – they are appended one after another.
- The content of
<slot>
element is used as a fallback. It’s shown if there are no light children for the slot.
The process of rendering slotted elements inside their slots is called “composition”. The result is called a “flattened DOM”.
Composition does not really move nodes, from JavaScript point of view the DOM is still same.
JavaScript can access slots using methods:
slot.assignedNodes/Elements()
– returns nodes/elements inside theslot
.node.assignedSlot
– the reverse property, returns slot by a node.
If we’d like to know what we’re showing, we can track slot contents using:
slotchange
event – triggers the first time a slot is filled, and on any add/remove/replace operation of the slotted element, but not its children. The slot isevent.target
.- MutationObserver to go deeper into slot content, watch changes inside it.
Now, as we know how to show elements from light DOM in shadow DOM, let’s see how to style them properly. The basic rule is that shadow elements are styled inside, and light elements – outside, but there are notable exceptions.
We’ll see the details in the next chapter.
Topics in Part 1
- Getting to know JavaFX
- Creating and starting a JavaFX Project
- Using Scene Builder to design the user interface
- Basic application structure using the Model-View-Controller (MVC) pattern
Prerequisites
- Latest Java JDK 8 (includes JavaFX 8).
- Eclipse 4.4 or greater with e(fx)clipse plugin. The easiest way is to download the preconfigured distro from the e(fx)clipse website. As an alternative you can use an update site for your Eclipse installation.
- Scene Builder 8.0 (provided by Gluon because Oracle only ships it in source code form).
Eclipse Configurations
We need to tell Eclipse to use JDK 8 and also where it will find the Scene Builder:
Open the Eclipse Preferences and navigate to Java | Installed JREs.
Click Add…, select Standard VM and choose the installation Directory of your JDK 8.
Remove the other JREs or JDKs so that the JDK 8 becomes the default.
Navigate to Java | Compiler. Set the Compiler compliance level to 1.8.
Navigate to the JavaFX preferences. Specify the path to your Scene Builder executable.
Helpful Links
You might want to bookmark the following links:
- Java 8 API - JavaDoc for the standard Java classes
- JavaFX 8 API - JavaDoc for JavaFX classes
- ControlsFX API - JavaDoc for the ControlsFX project for additional JavaFX controls
- Oracle’s JavaFX Tutorials - Official JavaFX Tutorials by Oracle
Now, let’s get started!
Create a new JavaFX Project
In Eclipse (with e(fx)clipse installed) go to File | New | Other… and choose JavaFX Project.
Specify the Name of the project (e.g. AddressApp) and click Finish.
Remove the application package and its content if it was automatically created.
Create the Packages
Right from the start we will follow good software design principles. One very important principle is that of Model-View-Controller (MVC). According to this we divide our code into three units and create a package for each (Right-click on the src-folder, New… | Package):
ch.makery.address
- contains most controller classes (=business logic)ch.makery.address.model
- contains model classesch.makery.address.view
- contains views
Note: Our view package will also contain some controllers that are directly related to a single view. Let’s call them view-controllers.
Create the FXML Layout File
There are two ways to create the user interface. Either using an XML file or programming everything in Java. Looking around the internet you will encounter both. We will use XML (ending in .fxml) for most parts. I find it a cleaner way to keep the controller and view separated from each other. Further, we can use the graphical Scene Builder to edit our XML. That means we will not have to directly work with XML.
Right-click on the view package and create a new FXML Document called PersonOverview
.
Design with Scene Builder
Right-click on PersonOverview.fxml
and choose Open with Scene Builder. Now you should see the Scene Builder with just an AncherPane (visible under Hierarchy on the left).
(If Scene Builder does not open, go to Window | Preferences | JavaFX and set the correct path to your Scene Builder installation).
Select the Anchor Pane in your Hierarchy and adjust the size under Layout (right side):
Add a Split Pane (Horizontal Flow) by dragging it from the Library into the main area. Right-click the Split Pane in the Hierarchy view and select Fit to Parent.
Drag a TableView (under Controls) into the left side of the SplitPane. Select the TableView (not a Column) and set the following layout constraints to the TableView. Inside an AnchorPane you can always set anchors to the four borders (more information on Layouts).
Go to the menu Preview | Show Preview in Window to see, whether it behaves right. Try resizing the window. The TableView should resize together with the window as it is anchored to the borders.
Change the column text (under Properties) to “First Name” and “Last Name”.
Select the TableView and choose constrained-resize for the Column Resize Policy (under Properties). This ensures that the colums will always take up all available space.
Add a Label on the right side with the text “Person Details” (hint: use the search to find the Label). Adjust it’s layout using anchors.
Add a GridPane on the right side, select it and adjust its layout using anchors (top, right and left).
Add the following labels to the cells.
Note: To add a row to the GridPane select an existing row number (will turn yellow), right-click the row number and choose “Add Row”.Add a ButtonBar at the bottom. Add three buttons to the bar. Now, set anchors (right and bottom) to the ButtonBar so it stays in the right place.
Now you should see something like the following. Use the Preview menu to test its resizing behaviour.
Create the Main Application
We need another FXML for our root layout which will contain a menu bar and wraps the just created PersonOverview.fxml
.
Create another FXML Document inside the view package called
RootLayout.fxml
. This time, choose BorderPane as the root element.Open the
RootLayout.fxml
in Scene Builder.Resize the BorderPane with Pref Width set to 600 and Pref Height set to 400.
Add a MenuBar into the TOP Slot. We will not implement the menu functionality at the moment.
The JavaFX Main Class
Now, we need to create the main java class that starts up our application with the RootLayout.fxml
and adds the PersonOverview.fxml
in the center.
Right-click on your project and choose New | Other… and choose JavaFX Main Class.
We’ll call the class
MainApp
and put it in the controller packagech.makery.address
(note: this is the parent package of theview
andmodel
subpackages).
The generated MainApp.java
class extends from Application
and contains two methods. This is the basic structure that we need to start a JavaFX Application. The most important part for us is the start(Stage primaryStage)
method. It is automatically called when the application is launched
from within the main
method.
As you see, the start(...)
method receives a Stage
as parameter. The following graphic illustrates the structure of every JavaFX application:
Image Source: http://www.oracle.com
It’s like a theater play: The Stage
is the main container which is usually a Window
with a border and the typical minimize, maximize and close buttons. Inside the Stage
you add a Scene
which can, of course, be switched out by another Scene
. Inside the Scene
the actual JavaFX nodes like AnchorPane
, TextBox
, etc. are added.
For more information on this turn to Working with the JavaFX Scene Graph.
Open MainApp.java
and replace the code with the following:
The various comments should give you some hints about what’s going on.
If you run the application now, you should see something like the screenshot at the beginning of this post.
Java Slot Machine Example Python
Frequent Problems
If JavaFX can’t find the fxml
file you specified, you might get the following error message:
java.lang.IllegalStateException: Location is not set.
To solve this issue double check if you didn’t misspell the name of your fxml
files!
Slot Machine Simulation Java Program
What’s Next?
In Tutorial Part 2 we will add some data and functionality to our AddressApp.