重写文本框JTextField添加图标

public class HFDoubleTextField extends JTextField {
	
	private static final long serialVersionUID = -2213492965585762616L;
	private ImageIcon icon;
	
	public HFDoubleTextField(int columns) {
		super(columns);
		//获取当前路径下的图片
		icon = new ImageIcon(Resources.class.getResource("double.png"));
		Insets insets = new Insets(2, 20, 2, 16);
		//设置文本输入距左边20
		this.setMargin(insets);
	}
	
	public HFDoubleTextField() {
		super();
		//获取当前路径下的图片
		icon = new ImageIcon(Resources.class.getResource("double.png"));
		Insets insets = new Insets(2, 20, 2, 16);
		//设置文本输入距左边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);
	}
}

  效果:

注意事项:

Insets insets = new Insets(0, 20, 0, 0); 如果你只这样插入内边距的话,
会导致的你的文本框上下比正常文本框要矮,但是要更框。

以为正常文本框的的边距是2,
所有要设成
Insets insets = new Insets(2, 20, 2, -16);

 

posted @ 2022-04-19 08:36  信铁寒胜  阅读(201)  评论(0编辑  收藏  举报