SlideShare a Scribd company logo
DesktopApps.pptx
[LRN1413 – JavaOne 2022]
Phil Race and Kevin Rushforth.
Java Desktop UI Client Team,
Java Platform Development Group, Oracle
Building and Deploying Java
ClientDesktop Applications
With JDK 17and Beyond
Agenda
3 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
• Whya desktop application ?
• Quick high-level overview of the JavaFX and Swing APIs
• DEMO an email desktop client application
• Showhowthe UIwas built
• Show how to create a deployment package for the app
• Re-examine the DEMO having explained how it was built
• Summary
Why a desktop application ?
4 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
• To access desktop features not easily delivered in a browser such as
• multi-window,multi-screen,
• O/S and desktop integration
• A better development experience
• maintainability,
• stability,
• control over the execution platform.
• ability to use platform libraries, native code via JNI (and in the future Project Panama)
• A better overall experience for the user
• Performance
• Responsiveness
• Easy to access application.
Swing[*] vs JavaFX as UI toolkits
5 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
At a distance there's a lot of similarity between the Swing/AWT/2D APIs and JavaFX APIs
• Both offer a comprehensive set of UIcontrols, with event handling ,drag and drop, clip board, window
management ..
• Both support customization of the rendering of the UIcontrols
• Both provide graphics primitives and 2D geometry, transformations etc.
• Both supporting printing
[*]:Whenever we say or write just "Swing“ in this presentation we mean not just the Swing UItoolkit but
also Java 2D and AWT etc as a whole, since the old encompassing term of "JFC“ (Java Foundation
Classes) has fallen into dis-use. The phrase “JDK Client Libraries” is another wayof describing all these
that are part of Java SE.
Swing vs JavaFX as UI toolkits (continued)
6 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
• Both make use of hardware acceleration of rendering (under the covers)
• Both are high performance
• Both support a variety of layout managers sufficient for most applications
• Both support Accessibility (for Assistive Technologies)
• Both support I1
8N / L1
0N
• Both can be developed using your preferred IDE(Idea,Eclipse, NetBeans)
Swing and JavaFX strengths
7 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
But each also has some unique features or greater strengths
• Swing is bundled with OpenJDK as it is part of Java SE.
• JavaFX has some 3D support
• It is easier to extend Swing components
• Itis easier to style FX components
• Swing has richer text and imaging APIs
• JavaFX has built-in charting APIs
• JavaFX supports media (integrated audio and video), web, animation, effects
So which one do you choose ?
Swing and JavaFX can be used together !
8 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Fortunately it is notan either/or choice – you can use both.
They work together seamlessly in the same application - even in the same
window. Swing can be nested within JavaFX – and vice versa.
And you can then interoperate between the two of them to create a first class
desktop application
DEMO – UI for an email clientapplication (JMail)
9 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
• Uses both Swing and JavaFX showcasing both
• Focus is on being a first class desktop application.
• Uses only public APIs available in JDK 1
7and JavaFX 1
7
• Isinstalled using a platform installer created by the JDK’s jpackage tool.
• Disclaimer :the emphasis here is on the UI- it doesn't connect to an email server and so all email data
is static.
Creating the Jmail Desktop Application
10 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
• What we will show you is how we developed this application
• Wewill help you navigate past the overwhelming amount of javadoc documentation, guides and
tutorials focused on how to use specific APIs / UIcontrols [*]
• Wewill help you find the parts you need to use to assemble the application
• We will also showhowyou can easily mix JavaFX and Swing
• Along the waywe will use some of the powerful UIcontrols and capabilities of these APIs
• Then when you have the application, we will show how to deploy it.
- The take awaywill be you will be to apply this to build your own application for your use case.
[*]But you’ll still need these so for your reference
Creating a UIwith Swing:https://docs.oracle.com/javase/tutorial/uiswing.html
Creating a UIwith JavaFX:https:
//docs.oracle.com/javafx/index.html
Make a Splash !
11 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
until window
• Applications can take time to start if they need to load files, access network resources etc
• Good UIexperience gives immediate feedback that the App DIDget the message to launch
• Add on command line (NO coding required)
java -splash:images/DukeMailbox.png
• Or embed the image in the jar and reference from the Manifest (META-INF/MANIFEST.MF)
SplashScreen-Image: images/DukeMailbox.png
• For best results provide splash images for different screen DPIs :Duke.png, Duke125pct.png,
Duke150pct.png,Duke200pct.png. JDK automatically selects the best match
• Splash is automatically hidden on displaying first AWT Window.
• Use the java.awt.SplashScreen API to programmatically update or hide the Splash
• Jmail applies a fadeout effect on an un-decorated replacement window.
• javax.swing.Timer fires every 20ms and calls Window.setOpacity(getOpacity()-0.05)
is invisible.
JMail UI
JSplitPane
JTable
JSplitPane
JPanel with
JLabel
children
JEditorPane
JavaFX
TreeTableView
embedded in a
JFXPanel from
the JavaFX
Swing interop
module
JFrame
JToolBar
12 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Frame It!
13 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
• JMail uses a Swing JFrame with a tool bar
,folder list, messages list and message.
• The hierarchyof containers depends on howcomponents should be grouped and what should
happen on resize
• The folder list is a JavaFX TreeTableView embedded in a JFXPanel
• The Message list is a JTable, the message view is a JPanel with multiple children
• JSplitPane is used to allow the user to reapportion the size of each grouping
• The Message JPanel children are another Panel for To/From/Subject etc
• JEditorPane is used to display the HTML content of the message text
• A variable number of JPanels display in-line attachments and the attachment list
• Choose a LayoutManager flexible enough to handle all the children of a container
as the window is resized. GridBagLayout or SpringLayout are possibilities for AWT
. JavaFX has
GridPane, AnchorPane and simpler one such as HBox and VBox
GetNoticed!System Tray and Desktop Notifications
• Use the java.awt.SystemTray API
• Install a T
rayIcon for Jmail
• Add a PopupMenu
• Use it to provide notifications when newmail arrives (etc)
import java.awt.MenuItem;
import java.awt.PopupMenu’
import java.awt.SystemTray;
import java.awt.TrayIcon;
SystemTray systemTray = SystemTray.getSystemTray();
PopupMenu popupMenu = new PopupMenu();
MenuItem item = new MenuItem(“Compose New Message”);
popupMenu.add(item);
TrayIcon trayIcon = new TrayIcon(mailImage, “Jmail”, popupMenu);
systemTray.add(trayIcon);
14 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Respond to Desktop Events :Example : About Handler
import java.awt.Desktop; // Key class for desktop integration
import java.awt.desktop.AboutEvent;
import java.awt.desktop.AboutHandler;
class JMailAboutHandler implements AboutHandler {
public void handleAbout(AboutEvent aboutEvent) {
// display a modeless JDialog with info about JMail
…
…
}
///////////////////////////
if (Desktop.isDesktopSupported) {
Desktop dt = Desktop.getDesktop();
if (dt.isSupported(Desktop.ACTION.APP_ABOUT)) {
dt.setAboutHandler(new JMailAboutHandler();
}
}
///////////////////////////////
15 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
JavaFX/Swing InterOp :JFXPanel and SwingNode
16 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
JFXPanel – FX inside Swing
• Used to embed JavaFXcontent into a Swing JFrame
• JFXPanel is a Swing JComponent
• JFXPanel contains a JavaFX Scene
JFXPanel jfxPanel = new JFXPanel();
Platform.runLater(() -> {
var button = new Button("JavaFX: Click me");
button.setOnAction(e -> System.out.println("Hello from JavaFX!"));
var root = new VBox(button);
var scene = new Scene(root);
jfxPanel.setScene(scene);
});
swingPanel.add(jfxPanel, BorderLayout.CENTER);
JavaFX/Swing InterOp :JFXPanel and SwingNode
17 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
SwingNode :Swing inside FX
• Used to embed Swing content into a JavaFX Stage
• SwingNode is a JavaFX Node
• SwingNode contains a Swing JComponent
var jButton = new JButton("SwingNode: JButton");
jButton.addActionListener(e -> {
System.out.println("Swing: JButton in SwingNode");
});
var swingButton = new SwingNode();
swingButton.setContent(jButton);
Compose Yourself !– JavaFX window and controls
JavaFX Stage
Button
Buttons
Label
18 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
TextField
HTMLEditor
ContentHandling :Text
Ifcontent type is recognized, create a handler for it and pass it
the data and add a new control in-line in the message.
T
extis very straightforward.
import java.nio.files.*;
JComponent createTextPanel(String fileName) {
Path filePath = Path.of(fileName);
try {
text = Files.readString(filePath);
} catch (IOException e) {
}
return new JTextArea(text); // the important line
}
19 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
ContentHandling :Images
• Built-in support in JDK for PNG, GIF
,JPEG, TIFF
, BMP images
• Straightforward to load - but first check image size in a robust app.
• Scale image down to fit –some photo images are very large.
• Wrap it in a Swing JComponent to be layed out and painted.
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
..
BufferedImage image = ImageIO.read(imageFile);
..
class ImagePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, scaledWidth, scaledHeight, null);
}
}
20 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
ContentHandling :Media
class MediaControl {
// add Play etc to wrapped MediaView
}
public static JFXPanel createMediaContent(String urlString) {
Media media = new Media(urlString);
MediaPlayer mediaPlayer = new MediaPlayer(media);
MediaView mediaView = new MediaView(mediaPlayer);
MediaControl mediaControl = new MediaControl(mediaView) ;
var scene = new Scene(mediaControl);
var jfxPanel = new JFXPanel();
jfxPanel.setScene(scene);
return jfxPanel;
}
21 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
ContentHandling :HTML / Web using JavaFX
// urlString can be (1) local file (2) remote URL
public static JFXPanel createWebContent(String urlString) {
BorderPane root = new BorderPane();
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
webEngine.load(urlString);
root.setCenter(webView);
// add browser navigation controls to root
...
Scene scene = new Scene(root, 400, 300);
var jfxPanel = new JFXPanel();
jfxPanel.setScene(scene);
return jfxPanel;
}
22 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Content Handling :Swing Content
public class SwingContent extends JavaContent {
SwingContent(JPanel panel, String jarFileName) {
super(jarFileName); // loads the app from the jar
if (theUI instanceof JComponent swingUI) {
panel.setLayout(new BorderLayout());
panel.add(BorderLayout.CENTER, swingUI);
}
}
}
23 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
ContentHandling :JavaFX Content
public FXContent(JFXPanel jfxPanel, String jarFileName) {
super(jarFileName); // loads app
if (theUI instanceof Parent fxUI) {
var root = new BorderPane();
scene = new Scene(root);
root.setCenter(fxUI);
jfxPanel.setScene(scene);
}
}
24 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Content Handling :External applications
Not all content can be handled by the JavaFX and Swing built-in support, eg
• PDF docs
• Microsoft Office docs, OpenOffice docs, macOS Keynote presentations
• Sometimes you want content in an external application even if JDK can handle it.
Launch a known application from a path using java.lang.ProcessBuilder
String javaHome = System.getProperty("java.home", "");
String javaCmd = Path.of(javaHome, "bin", "java").toString();
new ProcessBuilder(javaCmd, “-jar”, “Pie.jar”).start();
Use the java.awt.Desktop handler to find the desktop content handler
Desktop.getDesktop().browse(new URI(https://openjdk.org)); // open platform web browser
Desktop.getDesktop().open(new File(“duke.pdf”); // open platform PDF viewer
25 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Whatisn’tin the demo ?
26 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Not enough time to create or show everything, but for your app also consider :
• Using a custom Swing L&F or CSSstyling of JavaFX controls
• Drag and Drop support
• Custom cursors
• Animation
• Graphic effects
• Etc …
Deploying JMail using the jpackage tool
27 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Step 1
- Build your JDK runtime containing both Swing and JavaFX
First create the JDK to include in the application based on JDK 19and OpenJFX 19using the JDK’s jlink
command line tool.
The commands assume
(1)JDK 1
9 is on the current PATH
(2)JDK 1
9 jmods are in $JAVA_HOME/jmods
(3)JavaFX 19jmods are in javafx-jmods-19
jlink --output jdk-19+javafx-19 
--module-path $JAVA_HOME/jmods:javafx-jmods-19 
--add-modules ALL-MODULE-PATH
Deploying JMail using the jpackage tool (continued)
28 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Step 2–Run the JDK’s jpackage command line tool
Nowissue the jpackage command - a basic example looks like
jpackage --main-jar jmail.jar --runtime-image jdk-19+javafx-19
--name JMail --input jmail.dir --dest jpkg.outdir
• This will create JMail.exe on Windows, JMail.dmg on MacOS
• Override as needed using appropriate options to create a macOS .pkg, Windows .msi ..Etc
Deploying JMail using the jpackage tool (continued)
29 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Since we are emphasizing being a 1stclass desktop app, you should look at jpackage platform options
Windows :Add app to the Windows Menu and have installer create a desktop shortcut.
Provide an application icon in Windows required format.
jpackage .. --win-menu --win-shortcut –icon jmail.ico ..
macOS :Specify name to be used on the menu bar
Provide application icon for use on the Dock in macOS format.
jpackage .. –mac-package-name "JMail App" –icon jmail.iconset/jmail.icons ...
• There are numerous other platform-specific options –refer to jpackage docs.
• Install the .exeor .dmg in the usual wayas any application.
• Docs on using jpackage are here:https://docs.oracle.com/en/java/javase/19/jpackage/
Re-examine the JMail app (DEM O)
30 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
Look at the JMail app again now we know how it was implemented
DEMO (time permitting) of running jpackage and installing the app
Summary
31 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
• Wehave covered how to build a modern desktop application using both the Swing and JavaFX APIs
• Wehave looked at the desktop integration features these provide
• Wehave seen how easy it is to handle multiple content types
• Wehave learned how to use jpackage to create platform installers
• We have provided pointers to documentation
Shortly after Oracle Cloudworld / JavaOne 2022 we expect to post some of the content we have covered
here for you to reviewcode etc at your leisure :https:
//cr
.openjdk.java.net/~prr/javaone/2022/
You now have the information you need to start to build your own Java desktop UIapplication.
MORE ABOUT JAVAFX: “JavaFX 19and Beyond” [LRN2615],THISroom, 2.30pm Thursday.
DesktopApps.pptx

More Related Content

PDF
JavaFX: A Rich Internet Application (RIA) Development Platform
DOCX
What is java fx?
PPTX
Java_Unit6pptx__2024_04_13_18_18_07.pptx
PDF
Beyond The Buzz: Pluggable JavaFX Corporate Applications
PPTX
What's new for JavaFX in JDK8 - Weaver
PPT
Slot04 creating gui
PDF
Virtual dev-day-java7-keynote-1641807
PPT
Swing is not dead
JavaFX: A Rich Internet Application (RIA) Development Platform
What is java fx?
Java_Unit6pptx__2024_04_13_18_18_07.pptx
Beyond The Buzz: Pluggable JavaFX Corporate Applications
What's new for JavaFX in JDK8 - Weaver
Slot04 creating gui
Virtual dev-day-java7-keynote-1641807
Swing is not dead

Similar to DesktopApps.pptx (20)

PPTX
JavaFX 2 - A Java Developer's Guide (San Antonio JUG Version)
PPTX
Java AWT and Java FX
PPTX
Introduction To JavaFX 2.0
PDF
The Brainify App - JavaFx
PPTX
Chapter 1 swings
PPTX
JavaFX 2 Using the Spring Framework
PPTX
Advance java prasentation
PDF
Java 2012 conference keynote - Java Strategy & Roadmap - WebLogic & GlassFish...
PPTX
JavaFX - Sketch Board to Production
PPT
Java Swing Handson Session (1).ppt
PPT
What is java fx?
PDF
PPTX
SwingApplet.pptx
PPTX
Migrating From Applets to Java Desktop Apps in JavaFX
PPTX
Java/Servlet/JSP/JDBC
PPTX
Java fx
PPT
java swing programming
PDF
JAVA SWING:Swing is a Java Foundation Classes [JFC] library and an extension ...
PPTX
JAVA SWING PPT FOR PROGRAMMING AND CODING
JavaFX 2 - A Java Developer's Guide (San Antonio JUG Version)
Java AWT and Java FX
Introduction To JavaFX 2.0
The Brainify App - JavaFx
Chapter 1 swings
JavaFX 2 Using the Spring Framework
Advance java prasentation
Java 2012 conference keynote - Java Strategy & Roadmap - WebLogic & GlassFish...
JavaFX - Sketch Board to Production
Java Swing Handson Session (1).ppt
What is java fx?
SwingApplet.pptx
Migrating From Applets to Java Desktop Apps in JavaFX
Java/Servlet/JSP/JDBC
Java fx
java swing programming
JAVA SWING:Swing is a Java Foundation Classes [JFC] library and an extension ...
JAVA SWING PPT FOR PROGRAMMING AND CODING
Ad

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
ai tools demonstartion for schools and inter college
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
DOCX
The Five Best AI Cover Tools in 2025.docx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPT
Introduction Database Management System for Course Database
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
L1 - Introduction to python Backend.pptx
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
top salesforce developer skills in 2025.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Online Work Permit System for Fast Permit Processing
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Understanding Forklifts - TECH EHS Solution
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Which alternative to Crystal Reports is best for small or large businesses.pdf
ai tools demonstartion for schools and inter college
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
The Five Best AI Cover Tools in 2025.docx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
How to Choose the Right IT Partner for Your Business in Malaysia
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Introduction Database Management System for Course Database
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
VVF-Customer-Presentation2025-Ver1.9.pptx
L1 - Introduction to python Backend.pptx
ISO 45001 Occupational Health and Safety Management System
How to Migrate SBCGlobal Email to Yahoo Easily
top salesforce developer skills in 2025.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Online Work Permit System for Fast Permit Processing
Ad

DesktopApps.pptx

  • 2. [LRN1413 – JavaOne 2022] Phil Race and Kevin Rushforth. Java Desktop UI Client Team, Java Platform Development Group, Oracle Building and Deploying Java ClientDesktop Applications With JDK 17and Beyond
  • 3. Agenda 3 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates • Whya desktop application ? • Quick high-level overview of the JavaFX and Swing APIs • DEMO an email desktop client application • Showhowthe UIwas built • Show how to create a deployment package for the app • Re-examine the DEMO having explained how it was built • Summary
  • 4. Why a desktop application ? 4 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates • To access desktop features not easily delivered in a browser such as • multi-window,multi-screen, • O/S and desktop integration • A better development experience • maintainability, • stability, • control over the execution platform. • ability to use platform libraries, native code via JNI (and in the future Project Panama) • A better overall experience for the user • Performance • Responsiveness • Easy to access application.
  • 5. Swing[*] vs JavaFX as UI toolkits 5 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates At a distance there's a lot of similarity between the Swing/AWT/2D APIs and JavaFX APIs • Both offer a comprehensive set of UIcontrols, with event handling ,drag and drop, clip board, window management .. • Both support customization of the rendering of the UIcontrols • Both provide graphics primitives and 2D geometry, transformations etc. • Both supporting printing [*]:Whenever we say or write just "Swing“ in this presentation we mean not just the Swing UItoolkit but also Java 2D and AWT etc as a whole, since the old encompassing term of "JFC“ (Java Foundation Classes) has fallen into dis-use. The phrase “JDK Client Libraries” is another wayof describing all these that are part of Java SE.
  • 6. Swing vs JavaFX as UI toolkits (continued) 6 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates • Both make use of hardware acceleration of rendering (under the covers) • Both are high performance • Both support a variety of layout managers sufficient for most applications • Both support Accessibility (for Assistive Technologies) • Both support I1 8N / L1 0N • Both can be developed using your preferred IDE(Idea,Eclipse, NetBeans)
  • 7. Swing and JavaFX strengths 7 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates But each also has some unique features or greater strengths • Swing is bundled with OpenJDK as it is part of Java SE. • JavaFX has some 3D support • It is easier to extend Swing components • Itis easier to style FX components • Swing has richer text and imaging APIs • JavaFX has built-in charting APIs • JavaFX supports media (integrated audio and video), web, animation, effects So which one do you choose ?
  • 8. Swing and JavaFX can be used together ! 8 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates Fortunately it is notan either/or choice – you can use both. They work together seamlessly in the same application - even in the same window. Swing can be nested within JavaFX – and vice versa. And you can then interoperate between the two of them to create a first class desktop application
  • 9. DEMO – UI for an email clientapplication (JMail) 9 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates • Uses both Swing and JavaFX showcasing both • Focus is on being a first class desktop application. • Uses only public APIs available in JDK 1 7and JavaFX 1 7 • Isinstalled using a platform installer created by the JDK’s jpackage tool. • Disclaimer :the emphasis here is on the UI- it doesn't connect to an email server and so all email data is static.
  • 10. Creating the Jmail Desktop Application 10 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates • What we will show you is how we developed this application • Wewill help you navigate past the overwhelming amount of javadoc documentation, guides and tutorials focused on how to use specific APIs / UIcontrols [*] • Wewill help you find the parts you need to use to assemble the application • We will also showhowyou can easily mix JavaFX and Swing • Along the waywe will use some of the powerful UIcontrols and capabilities of these APIs • Then when you have the application, we will show how to deploy it. - The take awaywill be you will be to apply this to build your own application for your use case. [*]But you’ll still need these so for your reference Creating a UIwith Swing:https://docs.oracle.com/javase/tutorial/uiswing.html Creating a UIwith JavaFX:https: //docs.oracle.com/javafx/index.html
  • 11. Make a Splash ! 11 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates until window • Applications can take time to start if they need to load files, access network resources etc • Good UIexperience gives immediate feedback that the App DIDget the message to launch • Add on command line (NO coding required) java -splash:images/DukeMailbox.png • Or embed the image in the jar and reference from the Manifest (META-INF/MANIFEST.MF) SplashScreen-Image: images/DukeMailbox.png • For best results provide splash images for different screen DPIs :Duke.png, Duke125pct.png, Duke150pct.png,Duke200pct.png. JDK automatically selects the best match • Splash is automatically hidden on displaying first AWT Window. • Use the java.awt.SplashScreen API to programmatically update or hide the Splash • Jmail applies a fadeout effect on an un-decorated replacement window. • javax.swing.Timer fires every 20ms and calls Window.setOpacity(getOpacity()-0.05) is invisible.
  • 12. JMail UI JSplitPane JTable JSplitPane JPanel with JLabel children JEditorPane JavaFX TreeTableView embedded in a JFXPanel from the JavaFX Swing interop module JFrame JToolBar 12 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 13. Frame It! 13 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates • JMail uses a Swing JFrame with a tool bar ,folder list, messages list and message. • The hierarchyof containers depends on howcomponents should be grouped and what should happen on resize • The folder list is a JavaFX TreeTableView embedded in a JFXPanel • The Message list is a JTable, the message view is a JPanel with multiple children • JSplitPane is used to allow the user to reapportion the size of each grouping • The Message JPanel children are another Panel for To/From/Subject etc • JEditorPane is used to display the HTML content of the message text • A variable number of JPanels display in-line attachments and the attachment list • Choose a LayoutManager flexible enough to handle all the children of a container as the window is resized. GridBagLayout or SpringLayout are possibilities for AWT . JavaFX has GridPane, AnchorPane and simpler one such as HBox and VBox
  • 14. GetNoticed!System Tray and Desktop Notifications • Use the java.awt.SystemTray API • Install a T rayIcon for Jmail • Add a PopupMenu • Use it to provide notifications when newmail arrives (etc) import java.awt.MenuItem; import java.awt.PopupMenu’ import java.awt.SystemTray; import java.awt.TrayIcon; SystemTray systemTray = SystemTray.getSystemTray(); PopupMenu popupMenu = new PopupMenu(); MenuItem item = new MenuItem(“Compose New Message”); popupMenu.add(item); TrayIcon trayIcon = new TrayIcon(mailImage, “Jmail”, popupMenu); systemTray.add(trayIcon); 14 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 15. Respond to Desktop Events :Example : About Handler import java.awt.Desktop; // Key class for desktop integration import java.awt.desktop.AboutEvent; import java.awt.desktop.AboutHandler; class JMailAboutHandler implements AboutHandler { public void handleAbout(AboutEvent aboutEvent) { // display a modeless JDialog with info about JMail … … } /////////////////////////// if (Desktop.isDesktopSupported) { Desktop dt = Desktop.getDesktop(); if (dt.isSupported(Desktop.ACTION.APP_ABOUT)) { dt.setAboutHandler(new JMailAboutHandler(); } } /////////////////////////////// 15 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 16. JavaFX/Swing InterOp :JFXPanel and SwingNode 16 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates JFXPanel – FX inside Swing • Used to embed JavaFXcontent into a Swing JFrame • JFXPanel is a Swing JComponent • JFXPanel contains a JavaFX Scene JFXPanel jfxPanel = new JFXPanel(); Platform.runLater(() -> { var button = new Button("JavaFX: Click me"); button.setOnAction(e -> System.out.println("Hello from JavaFX!")); var root = new VBox(button); var scene = new Scene(root); jfxPanel.setScene(scene); }); swingPanel.add(jfxPanel, BorderLayout.CENTER);
  • 17. JavaFX/Swing InterOp :JFXPanel and SwingNode 17 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates SwingNode :Swing inside FX • Used to embed Swing content into a JavaFX Stage • SwingNode is a JavaFX Node • SwingNode contains a Swing JComponent var jButton = new JButton("SwingNode: JButton"); jButton.addActionListener(e -> { System.out.println("Swing: JButton in SwingNode"); }); var swingButton = new SwingNode(); swingButton.setContent(jButton);
  • 18. Compose Yourself !– JavaFX window and controls JavaFX Stage Button Buttons Label 18 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates TextField HTMLEditor
  • 19. ContentHandling :Text Ifcontent type is recognized, create a handler for it and pass it the data and add a new control in-line in the message. T extis very straightforward. import java.nio.files.*; JComponent createTextPanel(String fileName) { Path filePath = Path.of(fileName); try { text = Files.readString(filePath); } catch (IOException e) { } return new JTextArea(text); // the important line } 19 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 20. ContentHandling :Images • Built-in support in JDK for PNG, GIF ,JPEG, TIFF , BMP images • Straightforward to load - but first check image size in a robust app. • Scale image down to fit –some photo images are very large. • Wrap it in a Swing JComponent to be layed out and painted. import java.awt.image.BufferedImage; import javax.imageio.ImageIO; .. BufferedImage image = ImageIO.read(imageFile); .. class ImagePanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, x, y, scaledWidth, scaledHeight, null); } } 20 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 21. ContentHandling :Media class MediaControl { // add Play etc to wrapped MediaView } public static JFXPanel createMediaContent(String urlString) { Media media = new Media(urlString); MediaPlayer mediaPlayer = new MediaPlayer(media); MediaView mediaView = new MediaView(mediaPlayer); MediaControl mediaControl = new MediaControl(mediaView) ; var scene = new Scene(mediaControl); var jfxPanel = new JFXPanel(); jfxPanel.setScene(scene); return jfxPanel; } 21 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 22. ContentHandling :HTML / Web using JavaFX // urlString can be (1) local file (2) remote URL public static JFXPanel createWebContent(String urlString) { BorderPane root = new BorderPane(); WebView webView = new WebView(); WebEngine webEngine = webView.getEngine(); webEngine.load(urlString); root.setCenter(webView); // add browser navigation controls to root ... Scene scene = new Scene(root, 400, 300); var jfxPanel = new JFXPanel(); jfxPanel.setScene(scene); return jfxPanel; } 22 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 23. Content Handling :Swing Content public class SwingContent extends JavaContent { SwingContent(JPanel panel, String jarFileName) { super(jarFileName); // loads the app from the jar if (theUI instanceof JComponent swingUI) { panel.setLayout(new BorderLayout()); panel.add(BorderLayout.CENTER, swingUI); } } } 23 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 24. ContentHandling :JavaFX Content public FXContent(JFXPanel jfxPanel, String jarFileName) { super(jarFileName); // loads app if (theUI instanceof Parent fxUI) { var root = new BorderPane(); scene = new Scene(root); root.setCenter(fxUI); jfxPanel.setScene(scene); } } 24 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 25. Content Handling :External applications Not all content can be handled by the JavaFX and Swing built-in support, eg • PDF docs • Microsoft Office docs, OpenOffice docs, macOS Keynote presentations • Sometimes you want content in an external application even if JDK can handle it. Launch a known application from a path using java.lang.ProcessBuilder String javaHome = System.getProperty("java.home", ""); String javaCmd = Path.of(javaHome, "bin", "java").toString(); new ProcessBuilder(javaCmd, “-jar”, “Pie.jar”).start(); Use the java.awt.Desktop handler to find the desktop content handler Desktop.getDesktop().browse(new URI(https://openjdk.org)); // open platform web browser Desktop.getDesktop().open(new File(“duke.pdf”); // open platform PDF viewer 25 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates
  • 26. Whatisn’tin the demo ? 26 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates Not enough time to create or show everything, but for your app also consider : • Using a custom Swing L&F or CSSstyling of JavaFX controls • Drag and Drop support • Custom cursors • Animation • Graphic effects • Etc …
  • 27. Deploying JMail using the jpackage tool 27 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates Step 1 - Build your JDK runtime containing both Swing and JavaFX First create the JDK to include in the application based on JDK 19and OpenJFX 19using the JDK’s jlink command line tool. The commands assume (1)JDK 1 9 is on the current PATH (2)JDK 1 9 jmods are in $JAVA_HOME/jmods (3)JavaFX 19jmods are in javafx-jmods-19 jlink --output jdk-19+javafx-19 --module-path $JAVA_HOME/jmods:javafx-jmods-19 --add-modules ALL-MODULE-PATH
  • 28. Deploying JMail using the jpackage tool (continued) 28 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates Step 2–Run the JDK’s jpackage command line tool Nowissue the jpackage command - a basic example looks like jpackage --main-jar jmail.jar --runtime-image jdk-19+javafx-19 --name JMail --input jmail.dir --dest jpkg.outdir • This will create JMail.exe on Windows, JMail.dmg on MacOS • Override as needed using appropriate options to create a macOS .pkg, Windows .msi ..Etc
  • 29. Deploying JMail using the jpackage tool (continued) 29 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates Since we are emphasizing being a 1stclass desktop app, you should look at jpackage platform options Windows :Add app to the Windows Menu and have installer create a desktop shortcut. Provide an application icon in Windows required format. jpackage .. --win-menu --win-shortcut –icon jmail.ico .. macOS :Specify name to be used on the menu bar Provide application icon for use on the Dock in macOS format. jpackage .. –mac-package-name "JMail App" –icon jmail.iconset/jmail.icons ... • There are numerous other platform-specific options –refer to jpackage docs. • Install the .exeor .dmg in the usual wayas any application. • Docs on using jpackage are here:https://docs.oracle.com/en/java/javase/19/jpackage/
  • 30. Re-examine the JMail app (DEM O) 30 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates Look at the JMail app again now we know how it was implemented DEMO (time permitting) of running jpackage and installing the app
  • 31. Summary 31 Oracle CloudWorld Copyright © 2022,Oracle and/or its affiliates • Wehave covered how to build a modern desktop application using both the Swing and JavaFX APIs • Wehave looked at the desktop integration features these provide • Wehave seen how easy it is to handle multiple content types • Wehave learned how to use jpackage to create platform installers • We have provided pointers to documentation Shortly after Oracle Cloudworld / JavaOne 2022 we expect to post some of the content we have covered here for you to reviewcode etc at your leisure :https: //cr .openjdk.java.net/~prr/javaone/2022/ You now have the information you need to start to build your own Java desktop UIapplication. MORE ABOUT JAVAFX: “JavaFX 19and Beyond” [LRN2615],THISroom, 2.30pm Thursday.