jtextfield设置圆角
时间: 2024-05-14 17:17:17 浏览: 7
要设置 JTextField 的圆角,可以使用 javax.swing.border 包中的 Border 类来定义一个圆角边框。以下是一个简单的示例代码:
```
import javax.swing.*;
import javax.swing.border.*;
public class RoundedTextField extends JTextField {
public RoundedTextField(int columns) {
super(columns);
setBorder(new RoundedBorder(10)); // 设置圆角边框
}
private class RoundedBorder extends AbstractBorder {
private int radius;
public RoundedBorder(int radius) {
this.radius = radius;
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(c.getBackground());
g2.fillRoundRect(x, y, width - 1, height - 1, radius, radius);
g2.setColor(Color.GRAY);
g2.drawRoundRect(x, y, width - 1, height - 1, radius, radius);
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(this.radius + 1, this.radius + 1, this.radius + 2, this.radius);
}
@Override
public Insets getBorderInsets(Component c, Insets insets) {
insets.left = insets.right = this.radius + 1;
insets.top = this.radius + 1;
insets.bottom = this.radius + 2;
return insets;
}
}
}
```
在这个代码中,我们定义了一个 RoundedTextField 类,它继承自 JTextField,并在构造函数中设置了圆角边框。圆角边框的实现是通过定义一个 RoundedBorder 类来实现的。在 RoundedBorder 类中,我们定义了 paintBorder 方法来绘制圆角边框,并通过 getBorderInsets 方法来设置边框的内边距。最后,我们将 RoundedBorder 类作为 JTextField 的边框来使用。