A Subclass of LayerUI for Decorating JTextField Based on Focus - Java Swing

Java examples for Swing:JTextField

Description

A Subclass of LayerUI for Decorating JTextField Based on Focus

Demo Code

import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.FocusEvent;

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

class SmartBorderUI extends LayerUI<JTextField> {
  @Override// w  w w  . ja va 2s.c  o m
  public void paint(Graphics g, JComponent layer) {
    super.paint(g, layer);

    Graphics gTemp = (Graphics2D) g.create();
    int width = layer.getWidth();
    int height = layer.getHeight();

    @SuppressWarnings("unchecked")
    JLayer<JTextField> myLayer = (JLayer<JTextField>) layer;

    JTextField field = (JTextField) myLayer.getView();

    Color bColor;
    if (field.hasFocus()) {
      bColor = Color.RED;
    } else {
      bColor = Color.BLUE;
    }

    gTemp.setColor(bColor);
    gTemp.drawRect(0, 0, width, height);
    gTemp.dispose();
  }

  @Override
  public void installUI(JComponent c) {
    super.installUI(c);

    JLayer layer = (JLayer) c;
    layer.setLayerEventMask(AWTEvent.FOCUS_EVENT_MASK);
  }

  @Override
  public void uninstallUI(JComponent c) {
    super.uninstallUI(c);

    JLayer layer = (JLayer) c;
    layer.setLayerEventMask(0);
  }

  @Override
  protected void processFocusEvent(FocusEvent e, JLayer layer) {
    layer.repaint();
  }
}

public class Main extends JFrame {
  private JLabel firstNameLabel = new JLabel("First Name:");
  private JLabel lastNameLabel = new JLabel("Last Name:");
  private JTextField firstName = new JTextField(10);
  private JTextField lastName = new JTextField(10);

  public Main(String title) {
    super(title);

    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    LayerUI<JTextField> ui = new SmartBorderUI();

    JLayer<JTextField> layer1 = new JLayer<>(firstName, ui);
    JLayer<JTextField> layer2 = new JLayer<>(lastName, ui);

    add(firstNameLabel);
    add(layer1);
    add(lastNameLabel);
    add(layer2);
  }

  public static void main(String[] args) {
      Main frame = new Main(
          "JLayer Test Frame");
      frame.pack();
      frame.setVisible(true);

  }
}

Related Tutorials