您的位置:首页 > 其它

Swinghacks——给文本控件添加图片背景

2013-02-25 15:37 357 查看
先看效果图,这是一个有背景图片的JTextField



如果用java做个email客户端 或者 便签程序,然后给输入控件加入一些背景图片的话,还是不错的。

当然还可以配合上一篇文章中写到的  自定义边框。

来看看实现原理,swing默认是没有设置背景图片的功能,那么还是需要利用paintComponent方法

有一点需要注意,在重写paintComponent之前把背景图片画好,然后调用super.paintComponent(g)画控件

这样可以保证控件内容覆盖在背景图片上面

上代码:

import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;

// put a texture in the background

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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: