继续牛刀(JTextField水印);

 

玩Swing 没点美感怎么行..嘿嘿 ^v^
怎么能沉迷与JTextField那种白色的背景呢???太单调的..看不出像我这么有美感的人..怎能让它显示出我认为不好看的东西!!下面就来解决JTextFiled!! 为他添加水印!
代码很简单:

效果图:


文本也可以帅起来~~~~~~~

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class WatermarkTextField extends JTextField {
  BufferedImage img;
  TexturePaint texture;
  
public WatermarkTextField(File file) throws IOException //临时就把异常往外抛了.
   super();                                                 //方法接收一个Image图片文件.
   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);
  }

//Main类我就不说了Java的基础.
  public static void main(String[] args) throws Exception {
   JFrame frame 
= new JFrame("Watermark JTextField Hack");
   frame.setLayout(
new GridLayout(1,2));
   JTextField textfield 
= new WatermarkTextField(new File("Image/水印.JPG"));
   textfield.setForeground(Color.white);
   textfield.setText(
"A Text Field");
   textfield.setSize(
120,30);
   frame.getContentPane().add(textfield);
   frame.getContentPane().add(
new JButton("前面那家伙真漂亮"));
   frame.setSize(
250,60);
   frame.setVisible(
true);
  }

}

posted on 2008-05-19 16:49 相信 阅读(687) 评论(0)  编辑  收藏 所属分类: Swing文章


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

公告

不显示applet

常用链接

留言簿(16)

我参与的团队

随笔档案

文章分类

文章档案

新闻档案

相册

swingchina 专业搞Swing的网站

搜索

最新评论

阅读排行榜

评论排行榜