22
Fri, Nov
1 New Articles

Swinging with JFC

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

When Java 1.0 was first introduced, Sun’s intended strategy for programming graphical user interfaces was to use its Abstract Window Toolkit (AWT) package. The AWT classes, however, had some limitations. For one, they lacked a few components that are considered standard for industrial-strength GUIs (specifically, trees, tables, and tabbed dialogs). Second, AWT had no direct support for advanced features like tool tips and keyboard mnemonics. Third, to get the first version of Java out the door quickly, Sun developed the AWT window components as a thin veneer covering the native windowing components of the various platform-specific implementations of a Java Virtual Machine (JVM). The result of AWT’s reliance on the native components was a set of components that had a different look and feel on various platforms.

A number of third-party vendors scrambled to fill the market hole left open by Sun, not the least of which was Microsoft with its Windows Foundation Classes (WFC) package of Java GUI components. But Sun soon came out with a new package of GUI components called the Java Foundation Classes (JFC). This package was initially distributed as a widely successful beta called Swing. Early adopters of Java were in such dire need of the advanced capabilities of the JFC package that they deployed commercial products using the Swing beta. The Swing name stuck: The JFC package in Java 2 is called javax.swing. The names Swing and JFC are used interchangeably in most Java literature (although JFC, which is a standard part of Java 2, includes quite a few things other than Swing, such as graphics and accessibility), and I use them so here. (For information on using the JFC components with Java 1.1, visit www.java400.net.)

The Swing package, with its JFC components, solved the problems inherent with the AWT components. Among its many new and advanced components, the Swing package contains components called JTree, JTable, and JTabbedPane. Also, all the components of the Swing package have methods for assigning tool tips and keyboard mnemonics. Furthermore, the Swing components are known as lightweight components because they don’t carry the extra burden of a native component, as did their ancestor AWT heavyweight classes. The lightweight feature of Swing components makes the look and feel of JFC applications standard across all platforms. In fact, the look and feel of a JFC application can be assigned. The default look and feel for an application is set to one that is “cross-platform” so it appears and behaves similarly on most platforms. You can, however, specifically set your Java GUI to the look and feel of Windows, Motif, or

Macintosh (or even odd ones like Heavy Metal) with a call to UIManager. However, you can easily set the look and feel specifically to be one of a variety (such as Windows, Motif, Organic, Metal, or Macintosh) or one made available by a third-party vendor or recent additions to the Swing classes.

JFC Intro

Extremely complex and sophisticated graphical applications have been developed with the components of the Swing package. For instance, the KAWA Integrated Development Environment (IDE) for Java (visit tek-tools.com/kawa/) was developed (with 100% Pure Java) by taking full advantage of the Swing components. Even sophisticated games with complex animation have been developed with Java and Swing. Whole books have been written on how to use JFC, but you need to know only a few basics to develop business applications with Swing.

Figure 1 shows the standard JFC components you can use to develop many of your applications. Note that your AWT knowledge will be leveraged when you are developing JFC applications. Java is an object-oriented language: When the developers at Sun decided to create advanced GUI components, they built them on top of the base AWT component java.awt.container. Each JFC component was then implemented to draw its own image rather than rely on a native component like AWT did. Most of the JFC components, however, that have a corresponding AWT component still have most of the same attributes, methods, and events as their corresponding AWT ancestor (with a few exceptions, such as JList). As your application design becomes more sophisticated, you may use some of the advanced JFC components.

Figure 2 shows a few of the more interesting ones.

Minimal JFC Application

The biggest problem AS/400 RPG programmers have with developing a Java GUI application is simply getting started. I’d like to provide you with a tutorial on a minimal JFC application that consists of only an application frame. It is my intent that you use the code from this application as a template for your own Java GUIs. As you can see in the application window shown in Figure 3, my minimal application has no functional purpose because it has no components in its frame. The Java source for the class called FrameOnly (shown in Figure 4) begins by importing two Java packages: javax.swing and java.awt.event. The need to import the javax.swing package is obvious: It contains the JFC components. But you might be wondering why I’ve imported an AWT package. As I mentioned earlier, the classes of the Swing package use the AWT 1.1 event model, and, as a result, the Swing window components often generate AWT events. The FrameOnly application had to import the AWT event package in order to handle the window-closing event (which it does by properly shutting down the application when the user closes the window). The FrameOnly class subclasses JFC’s JFrame class with the following syntax:

class FrameOnly extends JFrame

This style of designing a GUI application is typical of most JFC applications, since the JFrame (as its entry in the table of Figure 2 explains) is a top-level application window with a title. The FrameOnly application “bootstraps” itself in its main method by instantiating (creating) an object variable called gui (of the class FrameOnly). I call this process bootstrapping because FrameOnly’s main method metaphorically picks itself up by its bootstraps to load the application. The gui object variable of the main method then invokes the setVisible method, passing to that method a true value that forces the window frame to be displayed. This simple code of FrameOnly’s main method is all that the majority of your JFC applications will ever need. Most of the work involved in setting up

your application window is done in its constructor. (A constructor is a function that bears the same name as its class.)

Frame Construction

FrameOnly’s constructor method begins by setting the title and size of the window frame with calls to the setTitle and setSize methods. If this were an AWT application that extended AWT’s Frame class instead of JFC’s JFrame, the AWT app could start adding components directly to the window frame. But the JFrame component has an odd behavior that AWT’s Frame component does not have—the JFrame component does not allow you to add components directly to the JFrame object. All JFC applications have a topmost panel. The FrameOnly class, after setting its title and size, creates a JPanel object called topPanel and invokes a unique function called getContentPane. The getContentPane method retrieves a JFrame component (which the Sun designers call a root pane) and allows you to add a panel to that root component. To that topmost panel, you add the other components of the application. (This is why I always name my topmost panel topPanel.) The following two lines of code, therefore, will always be in your JFC applications:

JPanel topPanel = new JPanel();
getContentPane().add(topPanel);

After the topmost panel is created and set, your application can then begin to add the components required for your application GUI. My FrameOnly application, however, does nothing more than set up the window frame. The only other thing the FrameOnly constructor function does is handle the window close event by exiting the application. It handles this event easily with the following four lines of code:

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)

{System.exit(0);}
});

This code uses a bit of Java magic called an inner class. I will not explain inner classes here, because their design is moderately complex. Suffice it to say that you should use this snippet of code to shut down your JFC applications properly. In fact, I suggest that you use the FrameOnly class as a template for all your JFC applications.

Window Dressing

Now that you know how to build the frame for your applications, your next step is to flesh out your Java GUI by adding the JFC components that provide the user interface for the window frame. A brief explanation of this process will suffice: You select components from the list in Figure 1, instantiate them, and add those objects to the topmost panel. For example, if you want to add a label and a text field to the application, you insert the following lines in your JFC’s application constructor just after the code that creates the topmost panel:

JLabel prompt = new JLabel(“Enter stuff here:”);
topPanel.add(prompt);
JTextField entry = new JTextField(20);
topPanel.add(entry);

Figure 5 shows the resulting GUI prompt. For a few more examples of simple extensions for this minimal application, visit the download page for the December/January issue of AS/400 NetJava Expert (Web Edition) at www.midrangecomputing.com/anje. At this site, you’ll find several example JFC applications. One is FrameWithMenu, which

shows you how to add menus to your Java GUI, create tool tips, and add keyboard mnemonics. Another is FrameWithList, which shows you how to use JFC’s JList component. And a third example, FrameWithTabbed-Dialog, shows how easy it is to implement tabbed dialogs. For more information on these JFC examples, read my article “Getting Started with JFC,” available in the December AS/400 NetJava Expert (Web Edition).

Be a Swinger

Even though the Java Foundation Classes are powerful enough to support the most sophisticated of GUI applications and the slickest of advanced game software, JFC is still easy enough for Java neophytes to develop their own cool Java GUIs. So don’t let the thickness of the books available on JFC scare you away from developing with JFC. To use JFC, you really need to understand only a third or perhaps even a fourth of the content covered in those overbloated books. By following the standard JFC template application shown in this article and then adding components as required for you own application, you can easily craft your own GUI complete with menus, tool tips, and keyboard mnemonics. As you get more comfortable with Java and JFC, you can add more advanced features, like trees, tables, pop-up menus, and tabbed dialogs.

References and Related Materials

• “Getting Started with JFC,” Don Denoncourt, AS/400 NetJava Expert (Web Edition), December/January 1999/2000, www.midrangecomputing.com/anje
• Java/400: www.java400.net
• Kawa—The Simple Yet Powerful IDE: tek-tools.com/kawa/

JFC Component AWT Component Description

JApplet Applet Base class that is subclassed during the design of Java applets for Web-deployment JFrame Frame A top-level window that has a title, a border, and support for a menu bar; often subclassed for the creation of a Java application
JList List A list of selectable items
JPanel Panel Provides space in which an application can attach any other component, including other panels JMenuBar MenuBar A bar, used for the placement of menus, that appears immediately under a window frame
JMenu Menu A window that contains menu items
JMenuItem MenuItem Options, similar in function to a button, that are added to a menu
JPopupMenu PopupMenu A context-sensitive menu that appears with options that are relative to the current cursor position JTextField TextField A single-line text input area
JTextArea TextArea A multiline text area for displaying and editing text
JButton Button A graphical push button that the user can click
JCheckBox CheckBox A graphical component that is used to represent a boolean value such as true/false or yes/no JRadioButton RadioButton A group of mutually exclusive boolean values, only one of which can be true
JScrollPane ScrollPane A window that automatically scrolls horizontally and vertically to display information that otherwise could not be viewed with the amount of available window space

Figure 1: All of the original AWT components have analogous JFC components.

JFC Component Description

JSlider Lets the user graphically select a value by sliding a knob within a bounded interval JSplitPane Divides two (and only two) components
JTabbedPane Allows the user to switch between a group of components by clicking on a tab with a given title and/or icon JTable Presents data in a two-dimensional table format as a user-interface component
JTree Displays a set of hierarchical data as an outline

Figure 2: Some of the new “advanced” JFC components provide a more sophisticated user interface.

Figure 3: The JFrame component is a top-level application window that features a title and, optionally, a menu bar.

import javax.swing.*;
import java.awt.event.*;

class FrameOnly extends JFrame {

public static void main(String[] args) {

FrameOnly gui = new FrameOnly();

gui.setVisible(true);

}

FrameOnly () {

setTitle (“Frame Only JFC Application”);

setSize(300, 100);

JPanel topPanel = new JPanel();

getContentPane().add(topPanel);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)

{System.exit(0);}

});

}

}

Figure 4: Most of your JFC GUI applications will use similar code to set up the window frame.





Swinging_with_JFC05-00.png 610x204





Swinging_with_JFC05-01.png 595x197

Figure 5: JFC components are added to the topmost panel of your application’s GUI.

Don Denoncourt

Don Denoncourt is a freelance consultant. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Don Denoncourt available now on the MC Press Bookstore.

Java Application Strategies for iSeries and AS/400 Java Application Strategies for iSeries and AS/400
Explore the realities of using Java to develop real-world OS/400 applications.
List Price $89.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: