Decorating JTextFeild Components Using JLayer - Java Swing

Java examples for Swing:JLayer

Description

Decorating JTextFeild Components Using JLayer

Demo Code

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;

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;

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 BlueBorderUI();

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

    add(firstNameLabel);//w w w  .  j a v a 2  s.co m
    add(layer1);

    add(lastNameLabel);
    add(layer2);
  }

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

class BlueBorderUI extends LayerUI<JTextField> {
  @Override
  public void paint(Graphics g, JComponent layer) {
    super.paint(g, layer);
    Graphics gTemp = (Graphics2D) g.create();
    int width = layer.getWidth();
    int height = layer.getHeight();
    gTemp.setColor(Color.BLUE);
    gTemp.drawRect(10, 10, width, height);
    gTemp.dispose();
  }
}

Related Tutorials