Swinghacks——给文本控件添加图片背景
先看效果图,这是一个有背景图片的JTextField
如果用java做个email客户端 或者 便签程序,然后给输入控件加入一些背景图片的话,还是不错的。
当然还可以配合上一篇文章中写到的 自定义边框。
来看看实现原理,swing默认是没有设置背景图片的功能,那么还是需要利用paintComponent方法
有一点需要注意,在重写paintComponent之前把背景图片画好,然后调用super.paintComponent(g)画控件
这样可以保证控件内容覆盖在背景图片上面
上代码:
[java]
import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;
// put a texture in the background
www.zzzyk.com
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) {
//先画背景
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(texture);
g.fillRect(0,0,getWidth(),getHeight());
//然后画控件,不然控件内容就被背景覆盖了
super.paintComponent(g);
}
}
补充:软件开发 , Java ,