Using JLayer in Swing Applications in NetBeans 7

 

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 runtime.

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 File > 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. Uncheck the Create Main Class check box.

c. 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, WallPaperDemo.java

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


 

.

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


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

This method creates a 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.


 

.

In the createUI() method, add event handling code to the Reverse button.

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, reverses the String, and then 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 WallPaperDemo.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 following class to WallPaperDemo.java. Be sure to add the class after the last closing brace.

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, you are overriding the paint() method and passing an instance of this class,
along with the component to be decorated, to the JLayer constructor: public JLayer(V view, LayerUI<V> ui)

.

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

a. Add the following lines of code to the method as indicated in the screenshot below.


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

f.add(jlayer);

 

The first argument to the Layer constructor can be any class extending the java.awt.Component and 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.

b. Delete the line of code shown below:

f.add(createUI());

 

.

In the Projects pane, right-click WallPaperDemo.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


The 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 Field Validation feature of JLayer, you have to create a demo application. 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 the UI, add the createContent()method to the class.

 

private static JComponent createContent()
{
LayerUI<JFormattedTextField> layerUI = new ValidationLayerUI();

JLabel lblName = new JLabel("Number:");
JFormattedTextField txtName = new JFormattedTextField(new Long(25));
txtName.setColumns(16);
txtName.setFocusLostBehavior(JFormattedTextField.PERSIST);
txtName.setValue(25);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2,1));
panel1.add(lblName);
panel1.add(new JLayer<JFormattedTextField>(txtName, layerUI));

JLabel dateLabel = new JLabel("Date:");
panel1.add(dateLabel);
DateFormat dateFormat = DateFormat.getDateInstance();
JFormattedTextField dateField = new JFormattedTextField(dateFormat);
dateField.setColumns(16);
dateField.setFocusLostBehavior(JFormattedTextField.PERSIST);
dateField.setValue(new java.util.Date());

panel1.add(dateLabel);
panel1.add(new JLayer<JFormattedTextField>(dateField, layerUI));
return panel1;
}


This method performs the following operations.

  • Creates a JLayer UI.
  • Creates a JLabel, Number and a JFormattedTextField with a initial value of 25.
  • Creates a JPanel. The Layout manager for the panel is set to be GridLayoutManager with 2 rows and 1 column. JLabel and the JFormattedTextField are added to the JPanel.
  • Creates a JLabel and a JFormattedTextField. The initial value of the date field is set for the current date.
  • Adds the JLabel and JFormattedTextField to the JPanel.

 

.

Next add the method createUI() to the class.

public static void createUI() {

JFrame f = new JFrame ("FieldValidator");

JComponent content = createContent();
f.add (content); f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo (null);
f.setVisible (true);
}

 

The createUI() method performs the following:

  • Creates a JFrame instance and sets the title to "FieldValidator".
  • The JPanel instance created in method createContent() is added to the JFrame.
  • Other properties of the JFrame are set in this method.

 

.

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


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

 

To implement FieldValidation using JLayer, add the ValidationLayerUI 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 FieldValidator.java and choose Run File.

 

The output will be as below

 

.

You can test the application for the following input conditions.

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

 

b. Delete the initial date 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