Using the new JLayer Decorator for a password field : Swing « JDK 7 « Java

Using the new JLayer Decorator for a password field

import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayer;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.plaf.LayerUI;

public class Test extends JFrame {
  public static void main(String[] args) {
    Test window = new Test();

  public Test() {
    this.setSize(300, 100);
    LayerUI<JPanel> layerUI = new PasswordLayerUI();
    JLayer<JPanel> jlayer = new JLayer<JPanel>(getPanel(), layerUI);

  private JPanel getPanel() {
    JPanel panel = new JPanel(new BorderLayout());

    JPanel gridPanel = new JPanel(new GridLayout(1, 2));
    JLabel quantityLabel = new JLabel("Password");
    JPasswordField passwordField = new JPasswordField();
    panel.add(gridPanel, BorderLayout.CENTER);

    return panel;

class PasswordLayerUI extends LayerUI<JPanel> {

  private String errorMessage = "Password too short";

  public void paint(Graphics g, JComponent c) {
    FontMetrics fontMetrics;
    int height;
    super.paint(g, c);
    Graphics2D g2d = (Graphics2D) g.create();
    int componentWidth = c.getWidth();
    int componentHeight = c.getHeight();
    fontMetrics = g2d.getFontMetrics(c.getFont());
    height = fontMetrics.getHeight();
    g2d.drawString(errorMessage, componentWidth / 2 + 10, componentHeight / 2
        + height);

  public void installUI(JComponent component) {
    ((JLayer) component).setLayerEventMask(AWTEvent.KEY_EVENT_MASK);

  public void uninstallUI(JComponent component) {
    ((JLayer) component).setLayerEventMask(0);

  protected void processKeyEvent(KeyEvent event, JLayer layer) {
    JTextField f = (JTextField) event.getSource();
    if (f.getText().length() < 6) {
      errorMessage = "Password too short";
    } else {
      errorMessage = "";


Related examples in the same category

1.Creating a varying gradient translucent window
2.Handling multiple file selection in the FileDialog class
3.Managing the Opacity of a Window
4.Managing the Shape of a Window
5.Managing Window types
6.Mixing heavyweight and lightweight components
7.New border types in Java 7:RaisedSoftBevelBorder
8.New border types in Java 7:LineBorder width
9.New border types in Java 7:LoweredSoftBevelBorder
11.BorderFactory.createSoftBevelBorder(BevelBorder.LOWERED, Color.lightGray, Color.yellow)
12.Managing extra mouse buttons and high resolution mouse wheels
13.Using the NumericShaper.Range enumeration to support the display of digits