JTextField、JPasswordField设置圆角输入框

方法1:定义Border,然后给JTextField设置即可

摘自并整理:https://blog.csdn.net/u012093968/article/details/39316679

最好添加这句话g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)告诉绘制API我们需要平滑一点,

否则绘制出来会有很多锯齿哟。

 1 package com.xxx.xxx.xxx;
 2 
 3 import java.awt.Color;
 4 import java.awt.Component;
 5 import java.awt.Graphics;
 6 import java.awt.Graphics2D;
 7 import java.awt.Insets;
 8 import java.awt.RenderingHints;
 9 
10 import javax.swing.border.Border;
11 
12 /**
13  * Swing
14  * 设置圆角边框(可以自定义边框的颜色)
15  * 可以为button,文本框等人以组件添加边框
16  * 使用方法:
17  * JButton close = new JButton(" 关 闭 ");
18  * close.setOpaque(false);// 设置原来按钮背景透明
19  * close.setBorder(new RoundBorder());黑色的圆角边框
20  * close.setBorder(new RoundBorder(Color.RED)); 红色的圆角边框
21  * 
22  * @author Monsoons
23  */
24 
25 public class RoundBorder implements Border {
26     private Color color;
27 
28     private int arcH = 15;
29     private int arcW = 15;
30 
31     public RoundBorder() {
32         this(Color.BLACK);
33         // 如果实例化时,没有传值
34         // 默认是黑色边框
35     }
36 
37     public RoundBorder(Color color) {
38         this.color = color;
39     }
40 
41     public Insets getBorderInsets(Component c) {
42 
43         // top:可以调节光标与边枉的距离, 间接影响高度
44         // left:可以调节光标与边枉的距离
45         // bottom:可以调节光标与边枉的距离, 间接影响高度
46         // right:可以调节光标与边枉的距离
47         return new Insets(10, 15, 10, 15);
48     }
49 
50     public boolean isBorderOpaque() {
51         return false;
52     }
53 
54     // 实现Border(父类)方法
55     @Override
56     public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
57         //        g.setColor(color);
58         //        g.drawRoundRect(0, 0, c.getWidth() - 1, c.getHeight() - 1, arcH, arcW);
59 
60         Graphics2D g2d = (Graphics2D) g.create();
61 
62         g2d.setColor(color);
63         g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
64         g2d.drawRoundRect(0, 0, c.getWidth() - 1, c.getHeight() - 1, arcH, arcW);
65 
66         g2d.dispose();
67     }
68 }

猜你喜欢

转载自www.cnblogs.com/LiuYanYGZ/p/9329521.html
今日推荐