Swing之JTextField中添加图片

先看一张最终效果图:


1、继承来自JPasswordField的文本框

import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 *
 * @author WZH
 */
public class JTextFieldPassword extends JPasswordField {
    private ImageIcon icon;

    public JTextFieldPassword() {
//        获取当前路径下的图片
        icon = new ImageIcon(getClass().getResource("./lock.png"));
        Insets insets = new Insets(0, 20, 0, 0);
        //设置文本输入距左边20
        this.setMargin(insets);
    }
    
    @Override
    public void paintComponent(Graphics g) {
        Insets insets = getInsets();
        super.paintComponent(g);
        int iconWidth = icon.getIconWidth();
        int iconHeight = icon.getIconHeight();
        int Height = this.getHeight();
        //在文本框中画上之前图片
        icon.paintIcon(this, g, (insets.left - iconWidth)/2, (Height - iconHeight) / 2);
    }
}


2、继承来自JTextField的文本框

import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JTextField;

/**
 *
 * @author WZH
 */
public class JTextFieldUser extends JTextField {
    private ImageIcon icon;

    public JTextFieldUser() {
        //获取当前路径下的图片
        icon = new ImageIcon(getClass().getResource("./user.png"));
        Insets insets = new Insets(0, 20, 0, 0);
        //设置文本输入距左边20
        this.setMargin(insets);
    }
    
    @Override
    public void paintComponent(Graphics g) {
        Insets insets = getInsets();
        super.paintComponent(g);
        int iconWidth = icon.getIconWidth();
        int iconHeight = icon.getIconHeight();
        int Height = this.getHeight();
        //在文本框中画上之前图片
        icon.paintIcon(this, g, (insets.left - iconWidth)/2, (Height - iconHeight) / 2);
    }
}

在文本框中添加图片的方法主要就在重写JtextField的paintComponent(Graphics g)方法,先将图片绘制在文本框中,这里应该注意的是super.paintComponent(g)方法应该在图片绘制前调用,否则会出现图片未绘上后被清除的情况。

示例代码:http://download.csdn.net/detail/a78460750/6473359

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值