Using JLayer in Swing Applications using NetBeans 7

 

<Do not delete this text because it is a placeholder for the generated list of "main" topics when run in a browser>

Purpose

This tutorial demonstrates usage of JLayer component in Java Swing applications.

Time to Complete

Approximately 30 minutes.

Overview

JDK 7 introduces a new Swing component,JLayer that serves as a universal decorator for Swing components. This new component is implemented as the javax.swing.JLayer class, and is based upon JXLayer, a part of the Swing Helper project from Swing Labs.

The JLayer class is a flexible and powerful decorator for Swing components. It enables you to draw on components and respond to component events without modifying the underlying component directly.

Using a JLayer, you can put a LayerUI together with any existing Component. You can also change the composition of LayerUIs and Components at run time.

Software and Hardware Requirements

The following is a list of software requirements:

Prerequisites

Before starting this tutorial, you should have the software installed as listed under Software Requirements.

JLayer's support for Custom Painting.

To demonstrate the custom painting feature of JLayer. You have to create a demo application, which reverses text entered into a texrfield when a button is pressed. The demo application uses JLayer to paint a wallpaper pattern behind the user interface . Perform the following steps.

 

.

Create a New Project.

 

 

.

Select Java from the Categories column and Java Application from the Projects column and then click Next.


.

Perform the following steps.

a. Name the project JLayerDemo
b. Click Finish.

 

.

Right-click JLayerDemo Project and select New > Java Class .

 

.

Name the class WallPaperDemo, package name demo, and then click Finish.

 

.

Add the following import statements to the java class, WallPaper.java

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;


 

.

To create, the UI add the below method createUI(), to the class.


private static JPanel createUI()
{
JPanel panel1 = new JPanel ();
JLabel lblName = new JLabel ("Name:");
panel1.add (lblName);
JTextField txtName = new JTextField (20);
panel1.add (txtName);
JButton btnReverse = new JButton ("Reverse");
panel1.add (btnReverse);
return panel1;
}

This method creates UI with the follwing components -Jlabel,JTextField and a JButton.

These components are added to a JPanel and the panel is returned.

.

Next add the method createLayer() to the class.


public static void createLayer()
{
JFrame f = new JFrame("Wallpaper");
JPanel panel = createUI()
f.add(createUI());
f.pack ();
f.setSize(300, 200);
f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo (null);
f.setVisible (true);

}

This method adds the panel returned by the createUI() method to a JFrame. The method also sets the various properties of JFrame.


 

.

Add the following event handling code to Reverse, to the CreateUI() method.

ActionListener al;
al = new ActionListener ()
{
public void actionPerformed (ActionEvent ae)
{
String txt = txtName.getText ();
txt = new StringBuffer (txt).reverse().toString();
txtName.setText (txt);
}
};
btnReverse.addActionListener (al);

The Reverse button responds to the click event and retrieves the text entered in the JTextField, txtName and reverses the String and displays it in the textfield.

 

 

.

Next add the main method to the class. In the main method createLayer() is invoked.


public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{ public void run() {
createLayer();
} });
}

 

.

In the Projects pane, right-click CelsiusConverter.java and choose Run File.

 

 

.

You can test the application by entering a String in the Name field and then clicking Reverse.

 

Output with the reversed String will be as in the below screenshot. 

 

.

To create a WallPaper using JLayer .Add the below class to WallPaper.java

class WallpaperLayerUI extends LayerUI<JComponent>
{
@Override
public void paint(Graphics g, JComponent c)
{ super.paint(g, c);
Graphics2D g2 = (Graphics2D) g.create();
int w = c.getWidth();
int h = c.getHeight();
g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, .5f));
g2.setPaint(new GradientPaint(0, 0, Color.yellow, 0, h, Color.red));
g2.fillRect(0, 0, w, h);
g2.dispose();

}

}

JLayer delegates the handling of painting and input events to a LayerUI object, which performs the decoration.
Extend LayerUI and you can override various methods to enable custom painting and event handling.In this case we are overriding the paint() method.
Next pass an instance of this class, along with the component to be decorated, to the following JLayer constructor:


public JLayer(V view, LayerUI<V> ui)

.

To add the Wallpaper to the UI using JLayer.Modify the createLayer() method as below

1. Add the following code .


LayerUI layerUI = new WallpaperLayerUI();
JLayer jlayer = new JLayer(panel, layerUI);

The first argument to the JLayer constructor can be any class extending java.awt.Component, is the Swing component you want to decorate.
This component can be a JPanel or another container.
The container and all contained components will be decorated. The second argument identifies the decorator.

2. Delete the below code.

f.add(createUI());

 

.

In the Projects pane, right-click CelsiusConverter.java and choose Run File.

 

.

You can test the application by entering a String in the Name field and then clicking Reverse.

 

Output with the reversed String and WallPaper applied to the UI will be as in the below screenshot. 

 

 

Using JLayer for Validating Text Fields.


JLayer class can be used to decorate text fields to show if they contain valid data. The JLayer class is used to provide a visual indication for fields that have invalid data. When the ValidationLayerUI class paints the text field, it draws a red X if the field contents cannot be parsed.To demonstrate the custom painting feature of JLayer. You have to create a demo application, which reverses text entered into a texrfield when a button is pressed. The demo application uses JLayer to paint a wallpaper pattern behind the user interface . Perform the following steps.

 

.

Right-click JLayerDemo Project and select New > Java Class .

 

.

Name the class FieldValidatorDemo, package name demo, and then click Finish.


.

Add the following import statements to the java class, FieldValidator.java

import java.awt.*;
import java.text.*;

import javax.swing.*;
import javax.swing.plaf.LayerUI;

 

.

To create UI add a method createContent() to the class and add the below code to the method.

This method perorms the following operations.

1.Creates a JLayer UI.

2.Creates a JLabel , JFormattedTextField with a initial value of 25.

3. Creates a JPanel.The Layout manager for the panel is set to be GridLayoutManager with 2 rows and 1 column. JLabel and the JFormattedTextField created in step2 is added to the JPanel.

4. Creates a JLabel Field,date . An instance of JFormattedTextField is created and its initial value is set for the current date .

5.Adds the JLabel and JFormattedTextField to the JPanel .

 

.

Next add the main method to the class. In the main method createContent() is invoked.


public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{ public void run() {
createContent();
} });
}

 

.

To implement FieldValidation using JLayer. Add the below class to FieldValidator.java

class ValidationLayerUI extends LayerUI<JFormattedTextField> {
@Override
public void paint (Graphics g, JComponent c) {
super.paint (g, c);

JLayer jlayer = (JLayer)c;
JFormattedTextField ftf = (JFormattedTextField)jlayer.getView();
if (!ftf.isEditValid()) {
Graphics2D g2 = (Graphics2D)g.create();

// Paint the red X.
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = c.getWidth();
int h = c.getHeight();
int s = 8;
int pad = 4;
int x = w - pad - s;
int y = (h - s) / 2;
g2.setPaint(Color.red);
g2.fillRect(x, y, s + 1, s + 1);
g2.setPaint(Color.white);
g2.drawLine(x, y, x + s, y + s);
g2.drawLine(x, y + s, x + s, y);
g2.dispose();
}
}
}

The class ValidationLayerUI is a LayerUI subclass and the paint() method is overridden to implement the FieldValidation.

 

.

In the Projects pane, right-click CelsiusConverter.java and choose Run File.

 

The output will be as below

 

.

You can test the application for the following input coditions.

1. Delete the initial value in the Number Field . Output after FieldValidation will be as below

 

2. Delete the initial Data value displayed in the date field. Output after FieldValidation will be as below.

 

 

Summary

This tutorial describes some of the capabilities of the JLayer class. JLayer’s support for custom painting , event detection and Field Validation lets you improve the UI of individual components.

Resources

Credits

Hardware and Software Engineered to Work Together Copyright © 2011, Oracle and/or its affiliates. All rights reserved