Java LayerUI extend

Description

Java LayerUI extend

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

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

public class Main extends JPanel {

   public Main() {
      setLayout(new BorderLayout(10, 20));
      JPanel inputArea = new JPanel();
      JLabel emailLbl = new JLabel("Email");
      final JTextField emailFld = new JTextField(20);
      emailFld.setText("wrong email");
      LayerUI<JTextField> layerUI = new EmailValidationLayerUI();
      JLayer<JTextField> layeredEmail = new JLayer<>(emailFld, layerUI);

      inputArea.add(emailLbl);//  www .  j a  va  2 s.com
      inputArea.add(layeredEmail);

      add(inputArea, BorderLayout.NORTH);

      JComponent buttonArea = new JPanel(new FlowLayout(FlowLayout.RIGHT));
      final JButton saveButt = new JButton("Save");

      buttonArea.add(saveButt);
      add(buttonArea, BorderLayout.SOUTH);

   }

   public static void main(String[] args) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Main m = new Main();
      frame.add(m);
      frame.setSize(300, 210);
      frame.setVisible(true);
   }
}

class EmailValidationLayerUI extends LayerUI<JTextField> {
   @Override
   public void paint(Graphics g, JComponent comp) {
      super.paint(g, comp);

      JLayer jlayer = (JLayer) comp;
      JTextField emailFld = (JTextField) jlayer.getView();
      String text = emailFld.getText();
      String regEx = ".+@.+\\.[A-Za-z]+";

      int x = comp.getWidth() - 50;
      int y = (comp.getHeight() - 8) ;

      if (text.length() > 0 && !(text.matches(regEx))) {
         Graphics2D g2 = (Graphics2D) g.create();
         g2.drawString("error", x, y);
         g2.dispose();
      } else if (text.length() > 0 && text.substring(text.lastIndexOf("."), text.length()).length() > 4) {
         Graphics2D g2 = (Graphics2D) g.create();
         g2.drawString("warning", x, y);
         g2.dispose();
      }
   }

}



PreviousNext

Related