Thursday, February 9, 2012

Introducing Swing and the JFC

Overview of Swing and Java Foundation Classes
The Java Foundation Classes (JFC) consists of a set of application programming interfaces (APIs) that are provided as part of the J2SE platform. JFC provides support for developing functional graphical user interfaces (GUIs).
It is also an expansion of the original Abstract Windowing Toolkit (AWT).
JFC consists of several APIs.
Swing is the latest Java GUI component kit extends the AWT API. It also includes a new set of GUI components, such as tables and trees, with a pluggable look and feel (PLAF).
The PLAF enables developers to design the appearance and behaviour of components or change the appearance and behaviour of components at runtime.
Swing is based on the Lightweight UI Framework. All the components of Swing are written only in Java. Swing is more customizable than AWT as you can modify borders, text, and colors.
All Swing components conform to a modified version of the Model-View-Controller (MVC) architecture. This is sometimes referred to as separate model architecture. In the Swing architecture, the model part of the component is treated as a separate element. The view and controller parts, however, are combined into a single object.
The AWT is the original GUI toolkit and the standard package that is provided with the Java Programming language. It contains base-level APIs that enables Java program to integrate into the native desktop window system on each platform.
The AWT includes a set of simple GUI components – such as lists, buttons, frames, and menus. These components enable you to create simple user interfaces (UIs), paint images, and graphics.
The AWT has a peer-based architecture, so native UI components are associated with specific AWT component. This enables them to run on a specific platform.
The Drag-and-drop API improves application interoperability. It enables data transfer, using the Drag-and-Drop mechanism, across Java and native applications.
By default, the GUI components in both AWT and Swing support the drag-and-drop capabilities of the Drag-and-Drop API.
The Java Accessibility API provides an interface that enables Java applications to interface with assistive technologies. These assistive technologies include screen readers, Braille terminals, and speech recognition devices.
To achieve maximum portability across platforms, the Java Accessibility API is written only in Java.
The Java 2D API is a set of classes that enable developers to include advanced two-dimensional (2D) graphics, text, and images into applets and applications.
The capabilities of Java 2D enable developers to create, store, and manipulate 2D objects. These objects can be rotated and bent to simulate 3D effects.
The Java 2D API is useful for applications that produce charts and graphs.
Java SE 6.0 introduced several enhancements to the AWT.
Splash screens are graphics that are displayed to users whenever a program is executed. A good example of a splash screen is the Windows logo that is shown during computer startup. Another example may be the company logos that animate while a computer game loads.
Splash screens are used to occupy and entertain users while they wait for the application to start.
Splash screens
Splash screens are graphics that are displayed to users whenever a program is executed. A good example of a splash screen is the Windows logo that is shown during computer startup. Another example may be the company logos that animate while a computer game loads.

Splash screens are used to occupy and entertain users while they wait for the application to start.

Prior to Java SE 6.0, any graphical representation of a program while loading could only be used after the Java Runtime Environment (JRE) had fully started. With the release of Java SE 6.0 – titled "Mustang" – splash screens are executed even when JRE is being initialized.

The easiest way to execute a splash screen is through the use of the
–splash command line switch.

The
–splash switch is used to define that an Image of type JPG, GIF, or PNG is shown prior to executing the Java application.

The syntax is

java –splash:Image_Name Program_Name

So to load and run a program that uses a splash screen you would type the following at the command line.

The code is
C:\java -splash:samplefile.gif SampleSplashScreen
In the example, the image specified as a splash screen at the command line is shown for at least three seconds as the SampleSplashScreen sleeps for at least three seconds. When Thread.sleep(3000) has finished its execution, the JFrame specified in the SampleSplashScreen is displayed. This replaces the image used as a splash screen.

The code to do this is
When using splash screens, you need to
·         ensure that the image used as a splash screen is in the same directory as the program to be executed
·         create a jar file type so that you can use a splash screen without using the –splash switch
·         ensure that the manifest file defines the splash screen that is used prior to executing the main class
To create the jar file, you use the jar -mcvf command.

The
–m switch specifies that a manifest file is used. The -c switch is used to create a new archive. The -v switch generates verbose output on screen. The –f switch specifies the name of the jar file.

The
Classes option specifies all of the Java classes required to execute the main class.

The syntax is

jar –mcvf Manifest_FileName Jarfile_Name Classes* Image_Name

To execute the jar file, you use the
java -jar command and specify the filename.

The syntax is

java –jar JarFile_Name

To make sure that the manifest file defines the splash screen that is used prior to executing the main class, you add the SplashScreen-Image command to the manifest file.
In this example, Class_Name is the name of the class to be executed. Image_Name is the name of the image used as the splash screen.
The System tray is the notification menu bar within your desktop. This is where all of the system applications that are currently running are shown as icons.

In Java SE 6.0, you can now place Java applications in the System tray. This is done using the
SystemTray class.

The
SystemTray class manipulates a single instance of the tray. To test and use the SystemTray class, you need to

The code example for adding an icon into the System Tray is as follows:
You first need to test whether the SystemTray class is supported by the current platform.

The code to do this is
if(SystemTray.isSupported()) {
  //do SystemTray instantiation
}

If the class is supported, you need to create an instance of the
SystemTray class.

The
getSystemTray() method retrieves the static single instance of the SystemTray class.

The code to do this is
SystemTray st = SystemTray.getSystemTray();

You need to create an icon to add to the System tray. You can do this by creating an instance of the
TrayIcon class.

In this example, you create an instance of the
Image class prior to creating the image used for the icon. The image is then assigned to the Image object using the getImage() method.

The code to do this is
Image image = Toolkit.getDefaultToolkit().getImage("ayos.jpg");
TrayIcon tray = new TrayIcon(image, "Did you see this?");

Finally, you add the
TrayIcon object to the System tray using the add() method.

The
TrayIcon object is used to represent the icons to be added into the System tray. The add() method is used to add the TrayIcon object into the System tray.

The code to do this is
st.add(tray);

With the release of Java SE 6.0, dialog boxes are now enhanced with four new distinct modal settings using the Dialog.ModalityType enumeration:MODELESS is the default modality. If a dialog box is set to MODELESS, it does not block any input or manipulation performed on other windows in an application.

In
APPLICATION_MODAL, all windows in the dialog box's owner hierarchy are restricted. However, if other windows are open, but are not part of the owner of the dialog box, any input to this window is still performed.TOOLKIT_MODAL is commonly used on browsers, and in particular applets. When an applet is loaded as modal, it blocks the other applets from accepting inputted information.DOCUMENT_MODAL is the enhanced version of APPLICATION_MODAL. It is specifically used whenever there are certain windows that need to be accessed on top of the current modal window. A good example of utilizing this modality is when you are creating a Help window.

In previous implementations of dialog modality, the
setModal() method specified if the dialog is Modeless (using set to false) or Application_Modal (using set to true).

With Java SE 6.0, this method has been replaced with the
setModalityType().

The code shows an example of using dialog modality:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SampleModal {
  SampleModal() {
  JFrame frame1 = new JFrame("JFrame 1");
  JFrame frame2 = new JFrame("JFrame 2");
  frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  JButton button1 = new JButton("One");
  JButton button2 = new JButton("Two");
  frame1.add(button1, BorderLayout.CENTER);
  frame2.add(button2, BorderLayout.CENTER);
  button1.addActionListener(new A());
  button2.addActionListener(new A());
  frame1.setBounds(100, 100, 200, 200);
  frame1.setVisible(true);
  frame2.setBounds(400, 100, 200, 200);
  frame2.setVisible(true);
  }
public static void main(String args[]) {
  new SampleModal();
}
class A implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    JButton source = (JButton)e.getSource();
    String text = getNewText(source);
    if (!JOptionPane.UNINITIALIZED_VALUE.equals(text) &&
            text.trim().length() > 0) {
      source.setText(text);
    }
  }
}
private static String getNewText(Component parent) {
  JOptionPane pane =new JOptionPane("Enter new Label",JOptionPane.QUESTION_MESSAGE);
  pane.setWantsInput(true);
  JDialog dialog = pane.createDialog(parent, "Enter Text");
  dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
  dialog.setVisible(true);
  return (String)pane.getInputValue();
}
}

To check the functions of the other modalities, simply change the values specified in
setModalityType to MODELESS, DOCUMENT_MODAL, or TOOLKIT_MODAL.

GIF writer
Displaying GIF image formats has always been supported by the Java platform. But since the patent disallowing the writing of GIF formats expired, support for GIF writing has been incorporated into the Java platform.

To write GIF formats, you can use the
ImageIO class of the javax.imageio package. The ImageIO class contains static methods that enable the encoding and decoding of images.

In IO operations,
InputStream and OutputStream or a Reader or Writer class is used to perform read and write operations. In a similar way, the ImageIO class utilizes an ImageReader and ImageWriter class to perform reading and writing operations on images.

The code shows an example of writing GIF formatted images:
import javax.imageio.*;
import java.io.*;
import java.awt.image.*;
import java.util.*;
public class SampleWriteGIF {
public static void main(String args[]) throws IOException {
  System.out.println("Listing Supported Writer Formats:");
  System.out.println(Arrays.toString(ImageIO.getWriterFormatNames()));
  if (args.length == 0) {
    System.out.println("Please input an image file");
    System.exit(0);
  }
  String name = args[0];
  File file = new File(name);
  BufferedImage input = ImageIO.read(file);
  File outputFile = new File(name+".gif");
  ImageIO.write(input, "GIF", outputFile);
}
}

In this example, a list of all available image formats is displayed first. These image formats are written using the
getWriterFormatNames() method.

Next the application checks for a command line input that specifies an image file to be converted into a GIF format. This image file is represented as a
File object, which is then read using the read() method of the ImageIO class. This is then passed to a BufferedImage object before writing the image into GIF format.

The image is then converted into a GIF format file using the
write() method of the ImageIO class.

The code to do this is:
import javax.imageio.*;
import java.io.*;
import java.awt.image.*;
import java.util.*;
public class SampleWriteGIF {
public static void main(String args[]) throws IOException {
  System.out.println("Listing Supported Writer Formats:");
  System.out.println(Arrays.toString(ImageIO.getWriterFormatNames()));
  if (args.length == 0) {
    System.out.println("Please input an image file");
    System.exit(0);
  }
  String name = args[0];
  File file = new File(name);
  BufferedImage input = ImageIO.read(file);
  File outputFile = new File(name+".gif");
  ImageIO.write(input, "GIF", outputFile);
}
}
Text anti-aliasing
Anti-aliasing is the effect of smoothing rendered text or images on screens that have discrete pixel values, commonly called "jaggies." This is done by drawing a lighter shade of color over the edges of these jaggies. This enables a smooth transition between the image's edges and that of the screen.

In Java SE 6.0, the normal grayscale color rendering has been enhanced for LCD screens by splitting each pixel into its component types or three columns of light - red, green, and blue. The transition between the image and the background becomes smooth and not jagged.


 
Overview of Swing

Swing is part of the JFC. It is a user interface component kit that you use to create GUIs for applets and applications. Swing is a peerless interface. It does not directly communicate with the APIs of the operating system on which it is running.
You can use Swing in applet development to provide browser users with rich and dynamic user interfaces.
Swing's accessibility feature makes it compatible with programs designed for people with special needs.
Swing is built on top of AWT. So it improves on AWT but does not replace it. Swing uses some AWT classes and extends its component classes.
Swing does not directly use AWT component classes because they contain native code. In other words, AWT is a peer interface.
The advantages of using Swing over AWT are
· Swing components are lightweight and more flexible
· Swing provides pluggable look-and-feel support
· Swing components can be built into programs using less code
Swing components are lightweight and more flexible
Swing components are referred to as lightweight components. They are written from scratch without using native code, Swing components are not based on platform-specific implementations, making them less prone to platform-specific bugs.

Swing components are more flexible and portable because they are only implemented in Java.
Swing provides pluggable look-and-feel support
Swing provides PLAF support. This enables developers to choose the behavior and appearance of the components in their programs.

Swing provides three look-and-feel modes:
·         Windows
·         Motif
·         Metal
Swing components can be built into programs using less code
Swing components can be built into programs using less code because Swing includes extensive functionality.

Swing components also use fewer system resources than AWT. This enables developers to produce smaller and more efficient applications.

Swing components
The Swing API contains components, containers, and controls.

A component is a software module, such as a text field, that is designed to be reused in many applications without being modified.

A container is a component - such as a window - that can hold other components. Controls are components that enable user input, such as buttons.
The Swing architecture is a modified version of the MVC architecture. In this architecture, each component consists of the following parts:
· the UIManager class
· the UI delegate
· the ComponentUI class
· the Component Model Interface
the UIManager class
The UIManager class controls the look-and-feel characteristics of each Swing component by communicating with the component's UI object.
the UI delegate
Each generic component class in the Swing API manages its own view-and-controller responsibilities. When you create a Swing object, an appropriate UI delegate is automatically created. This is where the Swing component delegates its specific look-and-feel responsibilities.
the ComponentUI class
All UI delegates extend the ComponentUI class. This class provides most of the pluggable look-and-feel capabilities of Swing. The methods of the ComponentUI class deal with the installation and uninstallation of the UI. It also delegates a component's painting and geometry handling. Client programs should not directly invoke methods on this class.
the Component Model Interface
Because component design should focus on an application's data rather than its user interface, Swing defines a separate model interface for each component type. This interface can store and manipulate data or values. This provides Swing programs with the option of plugging in their own customized model implementations. The view is responsible for the display of data, whereas the controller looks after any business logic.
The naming convention for Swing components is

JComponent_Name
Note:
Only the component classes start with the letter J.
Consider a simple GUI that contains three Swing components:
· JSlider
· JCheckBox
· JTextField
JSlider
JSlider is a control that enables you to select a certain value by sliding a knob in a limited interval.
JCheckBox
JCheckBox is a control that you can select or deselect using a check mark.
JTextField
JTextField is a control that enables you to enter a single line of text.
Consider a more complex GUI that contains Swing components.
· JButton
· JComboBox
· JList
· JScrollBar
JButton
JButton is a control that implements a standard button. A JButton can be round or rectangular, and display images instead of text.
JComboBox
JComboBox is a control that combines a text field and a drop-down list. With the JComboBox, users can either type a value or select an item from the list.
JList
JList is a control in the form of a list where users can select an item by clicking it.
JScrollBar
JScrollBar is a control that enables users to scroll through a list of items. A JScrollBar can be vertical or horizontal.
A JTabbedPane component is a container that can consist of a number of labeled tabs. A JTabbedPane enables you to switch between the tabs by clicking each tab. Each tabbed page contains a number of components.
A JTree component is a control that displays a hierarchical list of data. This component enables you to quickly navigate through a complex file structure.

Summary
The Java Foundation Classes (JFC) are a set of application programming interfaces (API) provided as part of the Java platform to provide GUI development support. The JFC consists of the following APIs - Abstract Windowing Toolkit (AWT), Swing, Accessibility, Drag-and-Drop, and Java 2D.

Java SE 6.0 introduced several enhancements to the AWT including splash screen, System tray, dialog modality, GIF writer, and text anti-aliasing functionality.

Swing is a peerless GUI component kit that you use to create GUIs for applets and applications. Swing components are lightweight and have pluggable look-and-feel and accessibility capabilities. Swing components can also be built into programs using less code and they use fewer resources than AWT.

The Swing API contains components, containers, and controls. The Swing architecture consists of the
UIManager and ComponentUI classes, the UI delegate, and the Component Model Interface. When using Swing components, you should avoid using AWT components with them to ensure thread safety, and ensure that any applet or window that contains Swing components has a Swing top-level container at the root of the hierarchy.

1 comments:

It is amazing and wonderful to visit your site. Thanks for sharing such a useful information. We are also providing the best services click on below links to visit our website.
Oracle Fusion HCM Training
Workday Training
Okta Training
Palo Alto Training
Adobe Analytics Training

Post a Comment