Java Swing How to - Water mark text field








Question

We would like to know how to water mark text field.

Answer

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
//  ww  w.  j  a  v a 2  s.  com
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main{
  public static void main(String[] args) throws Exception{
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    JTextField textfield = new WatermarkTextField(new URL("http://www.java2s.com/style/download.png"));
    textfield.setText("www.java2s.com");
    frame.getContentPane().add(textfield);
    frame.pack();
    frame.setVisible(true);
  }
} 

class WatermarkTextField extends JTextField {
  BufferedImage img;

  TexturePaint texture;

  public WatermarkTextField(URL file)  {
    super();
    try {
      img = ImageIO.read(file);
    } catch (IOException e) {
      e.printStackTrace();
    }
    Rectangle rect = new Rectangle(0, 0, img.getWidth(null), img.getHeight(null));
    texture = new TexturePaint(img, rect);
    setOpaque(false);
  }

  public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setPaint(texture);
    g.fillRect(0, 0, getWidth(), getHeight());
    super.paintComponent(g);
  }



}