Java中Swing画圆角边框设置粗细问题
程序员文章站
2022-06-17 15:30:09
...
Swing自定义圆角边框设置粗细
Swing做界面需要用圆角边框,且继承Border的设置颜色、粗细功能
下面是一段网上搜索的代码:
(网页链接:https://blog.csdn.net/tokimemo/article/details/33722157)
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.border.LineBorder;
public class MyLineBorder extends LineBorder{
public MyLineBorder(Color color, int thickness, boolean roundedCorners) {
super(color, thickness, roundedCorners);
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Color oldColor = g.getColor();
Graphics2D g2 = (Graphics2D)g;
int i;
g2.setRenderingHints(rh);
g2.setColor(lineColor);
for(i = 0; i < thickness; i++) {
if(roundedCorners)
g2.drawRoundRect(x, y, width, height, 5, 5);
else
g2.drawRect(x, y, width, height);//实际中此循环语句需要修改
}
g2.setColor(oldColor);
}
}
应用之后效果为:
发现无论怎么改thickness的参数都无法改变粗细。
原因是该代码在实现画线的粗细时,是循环画线,但是在同一位置画线,只能是覆盖上一层的线,并不能改变线条的粗细。
在Graghics中改变画线粗细是调用setStroke方法。
所以修改代码为:
if (roundedCorners) {
g2.setStroke(new BasicStroke(thickness));
g2.drawRoundRect(x, y, width, height, 20, 20);
}