重写文本框JTextField添加图标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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);
    }
}

  效果:

注意事项:

1
Insets insets = new Insets(0, 20, 0, 0); 如果你只这样插入内边距的话,<br>会导致的你的文本框上下比正常文本框要矮,但是要更框。<br><br>以为正常文本框的的边距是2,<br>所有要设成
1
Insets insets = new Insets(2, 20, 2, -16);

 

posted @   信铁寒胜  阅读(223)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示