本RAR文件包含Java Swing中JButton组件美化技术的示例代码,实现按钮的圆角矩形、立体效果以及优化鼠标交互响应。
主要代码如下:
```java
@Override
public void paintIcon(Component cmp, Graphics g, int x, int y) {
Color lowerColor = new Color(235, 255, 235);
Color highColor = new Color(81, 184, 77);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON); // 设置抗锯齿
RoundRectangle2D.Float r2d = new RoundRectangle2D.Float(0, 0, btnWidth - 1, btnHeight - 1, 20, 20);
Shape clip = g2d.getClip();
g2d.clip(r2d);
GradientPaint paint = new GradientPaint(0.0F, 0.0F, lowerColor,
0.0F, btnHeight, highColor, true); // 渐变填充
g2d.setPaint(paint);
g2d.fillRect(0, 0, btnWidth, btnHeight);
g2d.setClip(clip);
paint = new GradientPaint(0, 0,
new Color(0, 0, 0),
0, btnHeight - 1,
new Color(100, 100, 100)); // 黑色边框
g2d.setPaint(paint);
g2d.drawRoundRect(0, 0, btnWidth - 1, btnHeight - 1, 20, 20);
paint = new GradientPaint(
0,
1,
new Color(0, 0, 0, (int)50),
0,
btnHeight -
(int)3,
new Color((int)255,
(int)255,
(int)255,
(int)100)); // 白色边框
g2d.setPaint(paint);
g2d.drawRoundRect(1, 1, btnWidth - 3, btnHeight - 3, 18, 18);
FontMetrics fm = g2d.getFontMetrics(boldFont);
int textWidth = fm.stringWidth(btnText); // 文本宽度
int textAscent = fm.getAscent();
g2d.setColor(hoverColor);
g2d.setFont(boldFont);
g2d.drawString(
btnText, (btnWidth - textWidth) / 2,
(btnHeight +
textAscent) / 2 -
2); // 文本渲染
}
```
这段代码实现了绘制一个带有渐变效果的圆角矩形按钮,包括填充颜色、边框以及文字显示。