Swing之JTextField中添加图片

先看一张最终效果图:

Swing之JTextField中添加图片_第1张图片


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

你可能感兴趣的:(Java-Swing)