Overview of JFC
JFC – Java Foundation Classes – collection of APIs. Provides GUI support as part of the Java 2 platform
JFC superset of AWT.
The JFC consists of several APIs,
1. AWT — Java’s original GUI toolkit. It was designed to enable the development of simple user interfaces (UIs) by providing a limited set of GUI objects, or components, such as buttons, frames, and menus. The AWT has a peer-based architecture in which native UI components, or peers, are associated with each AWT component to enable them to run on a specific platform.
2. Swing — latest Java GUI component kit. Written only in Java. All Swing components conform to the Model-View-Controller (MVC) architecture.
3. Accessibility — The Accessibility API provides an interface that enables assistive technologies to interact with JFC and AWT components. Assistive technologies include screenreaders, Braille displays, and speech recognition devices. For maximum portability across platforms, this API is written in pure Java.
- 4. Drag-and-Drop — The Drag-and-Drop API improves application interoperability because it provides the ability to drag and drop between a Java application and a native application. You must know which drop formats the native application can accept because the target drop area is handled from within the foreign application.
-
5. Java 2D — The Java 2D API is a set of classes that enable developers to easily incorporate advanced, high-quality 2D graphics, text, and images into applications and applets. Using Java 2D, you can create 2-dimensional objects and rotate or bend them to simulate 3-D effects. This API is useful for mathematical and charting applications. A Java 3D API is available but this doesn’t form part of the core API.
AWT provides the foundation on which many JFC classes are built and forms the basis of Swing. For example, Swing components directly extend AWT components such as Window, Dialog, and Frame.
Swing does not replace AWT. Swing is lightwieght. All the existing AWT classes can still be used, but they are not recommended due to the superiority of the Swing classes.
Swing is built on top of AWT, it uses some of the AWT utility classes such as Font, Color and Graphics and extends its component classes.
The JFrame and JDialog swing components directly extend the AWT Frame and Dialog classes.
For instance,
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
public class JFrame extends Frame implements WindowConstants, Accessible, RootPaneContainer
Why Swing Components are lightweight?
Swing components are referred to as lightweight components because they are not based on any platform-specific implementations and are written from scratch without using any native code. By contrast, the AWT creates a window that is native to its host environment. So Swing is flexible and portable because it doesn’t have the overhead of AWT.
AWT components display slightly differently, depending on the host environment. Swing components offer a more uniform look and feel across platforms.
“The main reason that Swing does not directly use any AWT components is that they contain native code - many Swing components simply provide a 100 percent Java implementation of the heavyweight AWT components.”
Swing provides pluggable look and feel (PLAF) support, which is one of the most valuable capabilities of the Swing toolkit. PLAF is complemented by the MVC model of Swing components.
![]()
1. Swing components and containers
Graphical user interface (GUI) applications consist of several user interface objects, including buttons, menus, windows, and panels. In Java, these graphical elements are known as components.
Containers – for example frames, windows, and dialogs – are components that control how other components are arranged onscreen by dividing them into groups. They also control how other components behave.
A component alerts its container whenever its size or position changes, so the container’s layout manager can automatically adjust the components it contains.
Note
A layout manager, if installed, is responsible for automatically laying out components in a container.
A GUI’s onscreen display consists of components organized by at least one top-level container. This is known as a component hierarchy. When creating a Java GUI application, you place each component in a container.
Swing is a Java-based user interface toolkit that contains a library of prewritten components.
Each Swing component inherits from the javax.swing.JComponent class. This class enables Swing to display graphics and access offscreen information in response to user input.
For instance,
//
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.AbstractButton
javax.swing.JButton
Swing is based on classes that it inherits from the Abstract Windowing Toolkit (AWT). The JComponent class derives from the Container class, which is a subclass of the Component superclass. AWT’s components derive from this class, which derives from the Object class.
As a result, the Swing and AWT component hierarchies are similar. For example, the top-level Swing containers – JFrame, JWindow, and JDialog – respectively extend the AWT classes Frame, Window, and Dialog. JApplet extends Applet.
The root container for a Swing applet is a JApplet and the root container for a standalone GUI application is a JFrame. Once you’ve created a root container, you can add components and other containers to the root.
For example, you can add windows or dialogs using the top-level containers JWindow or JDialog. You can also use the JComponent class or a JPanel – a generic container – to group components inside other containers.
Note
A JWindow is a window without a border and JFrame, which derives from JWindow, is a window with a border.
Each JFrame, JWindow, and JDialog has several panes:
- Root pane
- Layered pane
- Content pane
- Glass pane
- Root pane
- The root pane is an intermediate container that manages the layered pane, content pane, and glass pane, as well as a menu bar if necessary. You can paint multiple components or let the component handle mouse events by changing a container’s root pane settings.
- Layered pane
- The layered pane holds components arranged in overlapping layers, which enables you to add popup items to applications. It also directly contains the root pane’s content pane and its optional menu bar.
- Content pane
- To display components, you add them to the container’s content pane. The content pane, which covers the container’s display area, contains and manages all the root pane’s onscreen components except the menu bar. Java automatically creates a content pane for each new
JFrame or JWindow.
- Glass pane
- The glass pane is invisible by default, but you can use it to paint over components or to superimpose an image above other components. Like the root pane, you can also use it to enable components to catch input events.
In addition to the top-level containers, you can use low-level containers – such as JInternalFrames or JPanels – to create Multiple Document Interface (MDI) GUIs. Internal frames and panels subdivide the display area defined by top-level containers.
Usually, you add instances of the JInternalFrame to a desktop pane, JDesktopPane. Internal panes have root panes like regular JFrames, so there is little difference between setting up a GUI using JInternalFrames or setting up one using JFrames.
Once you’ve defined the necessary display areas for an application with containers and panes, you can add interface components such as radio buttons, scrollbars, and menus using Swing’s large collection of prewritten elements.
Question
Match each Swing container to its description.
Options:
JApplet
JComponent
JFrame
JPanel
JWindow
Targets:
- A generic low-level container
- The root class for all Swing components
- The root container for a standalone application
Answer
JPanel is a generic low-level container, JComponent is the root class for all Swing components, and JFrame is the root container for standalone applications.
JApplet is the root container for all Swing applets. Like the other top-level containers, it is based on a top-level AWT container.
All components in the Swing toolbox derive from the JComponent class – javax.swing.JComponent – which derives from AWT’s Container class.
All standalone Swing applications use a JFrame as their root container. You can add components to the content pane of the JFrame.
A JPanel is a generic low-level container used to group components inside other containers by subdividing the display area.
JWindow is a top-level Swing container that you can use to add a window to a Java application. By definition, a JWindow does not have a border.
2. The JComponent services
All Swing components – for example, JLabel, JButton, and JScrollPane – descend from the JComponent class. This class derives from the Container class and enables you to add components to containers.
The functionality for each JComponent is provided by its ComponentUI. How each component displays depends on the installed look and feel.
The JComponent class provides a wide variety of functionality to its instances. For example, you can
- customize component appearance
- check component state
- specify event handling
- paint components
- change the containment hierarchy
- lay out components
- get and set component size and position
- customize component appearance
- You can modify the appearance of components by selecting a border, foreground color, background color, font, and a cursor to display when hovering over the component. You can also make the component opaque.
- check component state
JComponent lets you check the state of components. For example, you can determine whether a component and its container are visible onscreen and whether a component is enabled to generate events in response to user input. You can also add tooltips and specify component names.
- specify event handling
JComponent enables you to customize event listeners for mouse clicks, mouse movements, key presses, or changes to components. You can also check which component contains a specific point or enable data transfer handling.
- paint components
- You can customize painting for any
JComponent or subclass of JComponent. You can also repaint a component, repaint a specific area of a component, and refresh the layout of a component and its containers.
- change the containment hierarchy
- You can add or remove components from a container. You can also find out how many components are in a container and determine a component’s root pane, direct container, and topmost container.
- lay out components
- You can add components using an absolute position or a layout manager. You can also get or set a component’s alignment and orientation, as well as the container’s layout manager. When using a layout manager, you can specify a preferred, maximum, or minimum size for each component.
- get and set component size and position
- You can set a component’s position according to a fixed position or relative to other components. However, some layout managers may ignore absolute positions. You can also retrieve information about a component’s current height, width, size, its position relative to its parent, and the width of its border.
The Swing API includes a vast collection of methods, but there are a number of commonly-used methods that you should be familiar with.
For example, you use the add method to add GUI components directly to containers or to their content panes. To remove a component from a container, you use the remove method.
To set the colors for a component, you use the setForeground and setBackground methods. To refresh a component, you use the repaint method. And you can use the setLayout method to specify a layout manager.
If you do not want to use a layout manager, you call the setSize method to set an absolute size for a frame or window. You can also use the setBounds method to set the width, height, and relative location for a component. However, an installed layout manager will override most manual settings.
Question
Which services does the JComponent class provide to its subclasses?
Options:
- Adding event handling
- Painting components
- Resizing components
- Setting the layout
Answer
The JComponent class enables its subclasses to add event handling, paint components, and resize components.
Option 1 is correct. You can add event listeners to handle mouse clicks, mouse movements, key presses, or changes to components.
Option 2 is correct. You can specify a foreground and a background color for components. You can also repaint a component or refresh the layout of a component and its containers.
Option 3 is correct. You can get and set a component’s current height, width, and size. You can also change its position and the width of its border.
Option 4 is incorrect. You set a layout against a container, which defines how contained components are presented on the display surface.
Question
The JComponent class enables you to customize the appearance of components and containers.
Which methods enable you to resize components?
Options:
setBounds
setLayout
setForeground
setSize
Answer
You can resize components using the setBounds and setSize methods.
Option 1 is correct. You use the setBounds method to set the width, height, and relative location for components in a container.
Option 2 is incorrect. You use the setLayout method, which is inherited from java.awt.Container, to specify a layout manager. If you use a layout manager, you resize components using the setBounds method.
Option 3 is incorrect. You use the setForeground and setBackground methods to set a component’s colors.
Option 4 is correct. If you do not want to use a layout manager, you can use the setSize method to specify an absolute size for components.
3. Using containers and components
Each Swing applet and application has a containment hierarchy with a top-level container at its root. For example, you create a dialog within a JFrame by adding a JDialog container to its content pane. You can then add various components and low-level containers, such as JButtons, JScrollBars, JTables, and so on.
Usually, you add components directly to containers using the add method. However, to add components to a JFrame or JWindow, you add the components to the container’s content pane. To do this, you retrieve the content pane for the frame or window using the getContentPane method.
After you’ve added a container, you need to make it visible. To do this, you use the setVisible method. You can use the isVisible method to determine whether or not a component is visible.
Once you’ve added components and containers, you can set
- size
- You can call the
setSize method to set an absolute size for a container. If you want the frame or window to automatically adjust itself to fit all its elements, you can call the pack method. The pack method ensures that the containers are not smaller than their preferred sizes.
- focus
- Interface items must be able to receive keyboard focus if users are to interact with them using the mouse and keyboard. Most components can receive focus by default, but you can specify this by calling the
setFocusable method. You can also request that a component receive focus by using the requestFocus method.
Suppose that you’re building a Swing application that displays a different message each time the user clicks an interface item. The completed application will contain a button, a checkbox, and three radio buttons.
To begin, you import the Swing and AWT packages. Then you declare a button called commonButton, a checkbox, a ButtonGroup called icecreams to contain the radio buttons, and the three radio buttons – radio1, radio2, and radio3.
// Import swing and awt classes
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
public class UsingButtons {
JButton commonButton ;
JCheckBox checkBox ;
ButtonGroup icecreams ;
JLabel label ;
JRadioButton radio1 ;
JRadioButton radio2 ;
JRadioButton radio3 ;
Then you create a new JFrame called frame and a JPanel called pane.
private void buildapp() {
// Fancy decorations
JFrame.setDefaultLookAndFeelDecorated(true) ;
// Create and set up the frame
JFrame frame = new JFrame("Buttons") ;
// A JPanel holds the contents
JPanel pane = new JPanel(new BorderLayout()) ;
You create a blank JLabel, called label, and add it to the JPanel using the add method.
To add the JPanel to the JFrame, you add the JPanel to the frame’s content pane using the getContentPane method.
// Create and add a label
label = new JLabel(" ") ;
pane.add(label, BorderLayout.CENTER) ;
// Add the JPanel to the frame
frame.getContentPane().add(pane, BorderLayout.CENTER) ;
You create a new JPanel, radiopane, which contains the three radio buttons. Then you add the button, checkbox, and the radiopane to the JPanel.
To set the focus on the button, you use the requestFocus method.
You can also set the format of the components, for example, the borders for each component.
// A JPanel will hold the contents
JPanel radiopane = new JPanel(new GridLayout(3,1)) ;
radiopane.add(radio1) ;
radiopane.add(radio2) ;
radiopane.add(radio3) ;
pane.add(commonButton, BorderLayout.NORTH) ;
pane.add(checkBox, BorderLayout.SOUTH) ;
pane.add(radiopane, BorderLayout.EAST) ;
commonButton.requestFocus() ;
To display the frame, you set the setVisible method to true.
You also want to resize the frame so that it has a width of 300 pixels and a height of 200 pixels. To do this, you use the setSize method to specify the frame’s size.
// Display the frame
frame.setSize(300, 200) ;
frame.setVisible(true) ;
The final Buttons application contains the button, the checkbox, and three radio buttons.
Question
You’re building an application that requires the user to type their user name and password. You’ve created a top-level JFrame container called frame.
Complete the code to make the frame visible onscreen.
JFrame frame = new JFrame("Text") ;
//Display the frame
MISSING CODE ;
}
Answer
To make the frame visible, you set the setVisible method to true by typing
frame.setVisible(true)
Question
You’ve created four components – a JTextField, a JPasswordField, a JFormattedTextField, and a JTextArea – and added them to a JPanel called pane.
Complete the code that adds the pane to the frame.
JPanel pane = new JPanel(new GridLayout(4,1));
confirm = new JTextField (25) ;
pass = new JPasswordField(20) ;
format = new JFormattedTextField(DateFormat.getDateInstance());
format.setValue(new Date());
format.setEnabled(false);
area = new JTextArea(10, 20) ;
pane.add(confirm);
pane.add(pass);
pane.add(format);
pane.add(area);
});
// Add the JPanel to the frame
MISSING CODE ;
//Display the frame
frame.setVisible(true);
}
Answer
You add the pane to the frame’s content pane using the getContentPane method as follows:
frame.getContentPane().add(pane) ;
Question
Which line of code specifies that the JFrame called frame has an absolute width of 450 pixels and an absolute height of 220 pixels?
Options:
frame.pack() ;
frame.setSize(220, 450) ;
frame.setSize(450, 220) ;
Answer
You specify an absolute position for the frame by using the setSize method as follows:
frame.setSize(450, 220) ;
Option 1 is incorrect. You call the pack method if you want the frame or window to automatically adjust itself to fit all its elements. This method ensures that the containers are no smaller than their preferred sizes.
Option 2 is incorrect. When using the setSize method, you specify the component’s width and then its height in pixels.
Option 3 is correct. The setSize method takes two parameters, width and height. Although this sets an absolute size, some layout managers may ignore this setting.
4. Building a basic Swing application
When you create a GUI, you can specify how each window reacts when the user clicks the Close button. You can also determine the default look and feel for windows.
To customize the way that windows and frames are decorated, you can call the JFrame class’s static setDefaultLookAndFeelDecorated method with a true value. For example, you can remove all decorations, specify custom settings, enable full-screen exclusive mode, or set the icon to use for the application. If you do not specify any custom settings, the application’s look and feel determines how windows are decorated.
This setting affects all the JFrames that you create afterwards. However, some layout managers may ignore this setting.
You use the setDefaultCloseOperation to determine what happens when users click the Close button. You can specify one of four actions:
HIDE_ON_CLOSE
DO_NOTHING_ON_CLOSE
EXIT_ON_CLOSE
DISPOSE_ON_CLOSE
HIDE_ON_CLOSE
- To hide the frame without exiting the window, you use the
HIDE_ON_CLOSE parameter. This is the default setting for JFrames and JDialogs.
DO_NOTHING_ON_CLOSE
- If you specify the
DO_NOTHING_ON_CLOSE operation, the application performs the actions specified in the WindowListener object’s windowClosing method. This is the default setting for internal frames.
EXIT_ON_CLOSE
- To ensure that the application exits using the
System exit method, you specify the EXIT_ON_CLOSE parameter. This parameter is particularly useful for applications – especially single-frame applications – but it is not recommended for applets.
DISPOSE_ON_CLOSE
- If you specify the
DISPOSE_ON_CLOSE parameter, the application automatically hides the frame and disposes of it if the user clicks the Close button. This frees up any resources that the window was using.
Suppose that you’re building a single-frame Swing application. To build a basic Swing application, you
- import the necessary packages
- ensure thread safety
- create and customize a top-level container and components
Because many Swing components inherit from AWT classes, you should import both the Swing and the AWT packages. You should also import the AWT classes that support event handling, java.awt.event.*.
// Import swing and awt classes
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
public class BasicSwingApp implements ActionListener {
Any GUI updates must be performed from within the event-dispatching thread in order to avoid threading issues.
To do this, you need to call the javax.swing.SwingUtilities.invokeLater method when creating or updating the application’s GUI. The invokeLater method requests that supplied code be executed from within the event-dispatching thread.
You pass a Runnable object to the invokeLater method. You then invoke createAndShowGUI from within the run method.
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI
javax.swing.SwingUtilities.invokeLater(
new Runnable() {
public void run() {
BasicSwingApp app = new BasicSwingApp () ;
app.createAndShowGUI() ;
}
}
);
}
}
Note
The related SwingUtilities.invokeAndWait method waits for the passed code to execute, whereas invokeLater returns immediately – the supplied code is executed asynchronously.
Since all standalone Swing applications use a JFrame as their top-level container, you create a JFrame.
Once you’ve created the top-level container, you populate it with the appropriate GUI components for this application.
In the code example, you add a JPanel, a JButton, and a blank JLabel. You add the label to the button, add the button to the panel, and add the panel to the frame.
// Create and set up the frame
JFrame frame = new JFrame("A basic Swing application") ;
// A JPanel will hold the contents
JPanel pane = new JPanel(new GridLayout(0, 1)) ;
// Create a button, add an event listener,
// and add it to the JPanel
JButton button = new JButton("JButton") ;
button.addActionListener(this) ;
pane.add(button) ;
button.requestFocus() ;
// Create and add a label
label = new JLabel(buttonClicks + "0") ;
pane.add(label);
// Add the JPanel to the frame
frame.getContentPane().add(pane, BorderLayout.CENTER) ;
Once you’ve added components, you can set the characteristics of the top-level container. In this case, you want the windows to use the program’s default look and feel. And because this is a single-frame application, you want the JFrame to exit when the user closes the window.
To do this, you call the setDefaultCloseOperation method for the JFrame with the EXIT_ON_CLOSE parameter and call the setDefaultLookAndFeelDecorated method with a true value.
private void createAndShowGUI() {
// Fancy decorations
JFrame.setDefaultLookAndFeelDecorated(true) ;
// Create and set up the frame
JFrame frame = new JFrame("A basic Swing application") ;
// Close application when close button clicked
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
Finally, you ensure that the container is visible onscreen by calling the setVisible method with a true value.
// Display the frame
frame.setSize(300, 200) ;
frame.setVisible(true) ;
}
Question
Suppose you’re creating a single-frame Swing application. You want the windows to use the decorations specified in the program’s default look and feel.
Call the method that enables you to do this.
private void createAndShowGUI() {
// Fancy decorations
JFrame.MISSING CODE(true) ;
Answer
You call the setDefaultLookAndFeelDecorated method with a true value to ensure that the windows are decorated according to the program’s default look and feel.
Question
Because you’re creating a single-frame application, you want the window to exit when the user clicks the Close button.
Complete the method to do this.
private void createAndShowGUI() {
// Fancy decorations
JFrame.setDefaultLookAndFeelDecorated(true) ;
// Create and set up the frame
JFrame frame = new JFrame("A basic Swing application") ;
// Close application when close button clicked
frame.setDefaultCloseOperation(JFrame.MISSING CODE) ;
Answer
To ensure that the window exits when the user clicks the Close button, you call the setDefaultCloseOperation method with the EXIT_ON_CLOSE parameter.
Question
Which method allows thread-safe GUI updates?
Options:
setDefaultCloseOperation
setDefaultLookAndFeelDecorated
invokeLater
Answer
The javax.swing.SwingUtilities.invokeLater method ensures thread safety.
Option 1 is incorrect. The setDefaultCloseOperation method determines what happens when a user closes the main application window.
Option 2 is incorrect. Calling the setDefaultLookAndFeelDecorated with a true value ensures that the application’s look and feel will determine how the windows are decorated.
Option 3 is correct. To ensure thread safety, you call the invokeLater method of the javax.swing.SwingUtilities class. Then you pass a Runnable object and create or update the GUI from within the run method.
Summary
Java graphical user interface (GUI) applications consist of user interface objects known as components. Containers control how components are arranged onscreen by dividing them into groups. Swing is a Java-based toolkit that contains a library of prewritten components, based on classes from the Abstract Windowing Toolkit (AWT).
Swing components descend from the JComponent class, which derives from the Container class. This class enables you to customize the display, check component state, specify event handling, paint components, and change the containment hierarchy.
You can add components to containers using the add method. You add components to a JFrame or JWindow using the getContentPane method. The setVisible method ensures that the container is visible onscreen.
You can customize the way that windows and frames are decorated using the setDefaultLookAndFeelDecorated method. The setDefaultCloseOperation determines what happens when users close windows. To build a basic Swing application, you import the necessary packages, ensure thread-safety, and create and customize a top-level container and components.
The code for a basic Swing application
// Import swing and awt classes
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BasicSwingApp implements ActionListener {
private static String buttonClicks = "Button clicks: ";
private int clicks = 0;
JLabel label;
// Provides an implementation of ActionListener.actionPerformed
public void actionPerformed(ActionEvent e) {
label.setText(buttonClicks + ++clicks);
}
private void createAndShowGUI() {
// Fancy decorations
JFrame.setDefaultLookAndFeelDecorated(true) ;
//Create and set up the frame
JFrame frame = new JFrame("A basic Swing application") ;
//Close application when close button clicked
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
// A JPanel will hold the contents
JPanel pane = new JPanel(new GridLayout(0, 1));
// Create a button, add an event listener,
// and add it to the JPanel
JButton button = new JButton("JButton");
button.addActionListener(this);
pane.add(button);
button.requestFocus();
// Create and add a label
label = new JLabel(buttonClicks + "0");
pane.add(label);
// Add the JPanel to the frame
frame.getContentPane().add(pane, BorderLayout.CENTER) ;
//Display the frame
frame.setSize(300, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI
javax.swing.SwingUtilities.invokeLater(
new Runnable() {
public void run() {
BasicSwingApp app = new BasicSwingApp () ;
app.createAndShowGUI();
}
}
);
}
}