JLayer

javax.swing.JLayer Example: A new Swing Feature in Java 7

This is a example for JLayer class in javax.swing package. JLayer is a new swing feature in Java 7. In this example, JLayer is used to decorate and validate the Text Field & Date Field in the User interface.

This article is built into two steps. The first step has the following:

  • Creation of Validator UI
  • createValidatorUI method is invoked in Runnable Class method run
  • In createValidatorUI method JFrame is created
  • In the second step the following is performed:

    • Validator Pane is created through createValidatorPane
    • ValidatorPane is added to the JFrame
    • in the createValidatorPane, JLayer is created with parameters TextField and ValidationLayer a subclass of Validation Layer

    There are two classes in this example:

    • JLayerValidator
    • Validation Layer

    1.JLayerValidator Class

    In JLayerValidator class, there are three methods main, createValidatorUI and createValidatorPane. In the createValidatorUI method, JFrame is created. JFrame consisting of Validator Box. Validator Box has integer field Panel and DateField Panel. JLayer TextField & Date Field are added to respective panel. Validation Layer object (instance of LayerUI subclass) is passed on to the parameter in the construction of JLayer for Text and Date Fields in createValidatorPane method.

    JLayer is instantiated using one with parameters view (panel in this example) and ValidationLayer a subclass of LayerUI in the createValidatorPane.

    JLayerValidator.java

    package com.javacodegeeks.JLayer;
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.text.DateFormat;
    import java.text.NumberFormat;
    
    import javax.swing.Box;
    import javax.swing.JComponent;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JLayer;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    import javax.swing.plaf.LayerUI;
    
    /**
     *This example demonstrates the usage of JLayer and LayerUI class
     * to decorate the text field and datefield
     * @author bhagvan kommadi
     *
     */
    public class JLayerValidator {
    
    	/**
             * Creating a validator UI
    	 *
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		javax.swing.SwingUtilities.invokeLater(new Runnable(){
    
    				public void run()
    				{
    					createValidatorUI();
    				}
    
    		}
    				);
    
    	}
    
    	/**
    	 * This method creates a JFrame and validator pane box
    	 * is added to the frame
    	 */
    	public static void createValidatorUI()
    	{
    		JFrame frame = new JFrame("ValidatorUI");
    
    		JComponent component = createValidatorPane();
    
    		frame.add(component);
    
    		frame.pack();
    
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		frame.setVisible(true);
    
    	}
    	
    	/**
    	 * This method creates the Vertical Box
    	 * Textfield and Date field panels are added
    	 */
    	 
    	private static JComponent createValidatorPane()
    	{
    
    	   Dimension labelDimension = new Dimension(100,30);
    
    	   Box box = Box.createVerticalBox();
    
    	   LayerUI validationLayer =  new ValidationLayer();
    
    	   JLabel integerJLabel = new JLabel("Integer");
    	   integerJLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    	   integerJLabel.setPreferredSize(labelDimension);
    
    	   NumberFormat integerFormat = NumberFormat.getInstance();
    	   JFormattedTextField integerTextField = new JFormattedTextField(integerFormat);
    	   integerTextField.setColumns(10);
    	   integerTextField.setFocusLostBehavior(JFormattedTextField.PERSIST);
    	   integerTextField.setValue(40);
    
    	   JPanel integerPanel = new JPanel();
    	   integerPanel.add(integerTextField);
    	   integerPanel.add(new JLayer(integerTextField,validationLayer));
    
    	   JLabel dateJLabel = new JLabel("Date");
    	   dateJLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    	   dateJLabel.setPreferredSize(labelDimension);
    
    	   DateFormat dateFormat = DateFormat.getDateInstance();
    	   JFormattedTextField dateTextField = new JFormattedTextField(dateFormat);
    	   dateTextField.setColumns(16);
    	   dateTextField.setFocusLostBehavior(JFormattedTextField.PERSIST);
    	   dateTextField.setValue(new java.util.Date());
    
    	   JPanel dateJPanel = new JPanel();
    	   dateJPanel.add(dateTextField);
    	   dateJPanel.add(new JLayer(dateTextField,validationLayer));
    
    	   box.add(Box.createGlue());
    	   box.add(integerPanel);
    	   box.add(Box.createGlue());
    	   box.add(dateJPanel);
    
    
    
    	   return box;
    
    	}
    
    
    
    	}
    

    2.Validation Layer Class

    ValidationLayer is a subclass of LayerUI for formatted textField.ValidationLayer subclass of LayerUI is instantiated with a default constructor. LayerUI class has methods paint, installUI and uninstallUI which are overridden in ValidationLayer. Paint method gives complete control over drawing a component. Panel is rendered to an offscreen image.

    ValidationLayer.java

            /**
    	 * This class is used for validation of
    	 *  fields. JLayer is instantiated using this
    	 *  instance as parameter
    	 *
    	 */
    	class ValidationLayer extends LayerUI
    	{
    		@Override
    
    		public void paint (Graphics graphics, JComponent component)
    		{
    			super.paint(graphics,component);
    
    			JLayer jLayer = (JLayer)  component;
    
    			JFormattedTextField formattedTextField = (JFormattedTextField) jLayer.getView();
    
    			if(!formattedTextField.isEditValid())
    			{
    
    				Graphics2D graphics2D = (Graphics2D) graphics.create();
    
    				graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    
    				int width = component.getWidth();
    
    				int height = component.getHeight();
    
    				int spacing = 10;
    
    				int padding = 5;
    
    				int x = width - padding - spacing;
    
    				int y = (height - spacing)/2;
    
    				graphics2D.setPaint(Color.red);
    				graphics2D.fillRect(x, y, spacing+1, spacing+1);
    				graphics2D.setPaint(Color.white);
    				graphics2D.drawLine(x,y, x+spacing, y+spacing);
    				graphics2D.drawLine(x,y+spacing,x+spacing, y);
    
    				graphics2D.dispose();
    
    
    
    			}
    
    
    
    		}
    	}
    
    
    Tip
    JLayer and LayerUI can be used for decoration and validating text fields. ValidationLayerUI class (source code enclosed) is used to show the data is invalid.

    3. Project Structure

    javax_swing_jlayer

    4. GUI

    jlayer_demo

    5. Closing Words

    JLayer can be implemented for decorating and validations. JLayer is a solution to do custom painting over compound component and catching input events from its subcomponents.

    6. Download Java Source Code

    Download
    You can download the eclipse project of this example: JLayerValidator

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button