package hack.
import javax.swing.*;
import java.awt.image.*;
import java.awt.*;
import *;
import javax.imageio.*;
public class WaterMarkTextField extends JTextField{
BufferedImage img;
TexturePaint texture;
public WaterMarkTextField(File file) throws IOException{
super();
img = ImageIO.read(file);
Rectangle rect = new Rectangle(0, 0,
img.getWidth(null), img.getHeight(null));
texture = new TexturePaint(img, rect);
// setOpaque(false); 这句不要
}
public void
paintComponent(Graphics g) {
//方法名错误
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(texture);
g.fillRect(0,0,getWidth(),getHeight()); //这两句话看不懂。其实觉得直接调用g.drawImage就行了
}
public static void main(String argv[]) throws Exception{
JFrame frame = new JFrame("A text field");
JTextField textfield = new WaterMarkTextField(
new File("bg.png"));
textfield.setText("Hello world");
frame.getContentPane().add(textfield);
frame.pack();
frame.setVisible(true);
}
}