Java LayerUI extend to add border to JTextField

Description

Java LayerUI extend to add border to JTextField

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.plaf.LayerUI;

class MyBorderLayerUI extends LayerUI<JTextField> {
  @Override/* w  w w.  j  av  a 2s .  com*/
  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<JTextField> layer = (JLayer<JTextField>) c;
    layer.setLayerEventMask(AWTEvent.FOCUS_EVENT_MASK);
  }

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

    JLayer<JTextField> layer = (JLayer<JTextField>) c;
    layer.setLayerEventMask(0);
  }

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

public class Main extends JFrame {


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

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

    JLabel firstNameLabel = new JLabel("First Name:");
    JTextField lastName = new JTextField(10);
    
    LayerUI<JTextField> ui = new MyBorderLayerUI();

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

    add(firstNameLabel);
    add(layer2);
  }

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



PreviousNext

Related