java画一个圆角矩形
时间: 2023-10-23 14:17:34 浏览: 74
要在Java中画一个圆角矩形,可以使用Graphics2D类的drawRoundRect()方法。示例代码如下:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RoundedRectangleExample extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// 将 Graphics 对象转换为 Graphics2D 对象以使用更多的功能
Graphics2D g2d = (Graphics2D)g;
// 设置抗锯齿,以便绘制更平滑的形状
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 绘制圆角矩形
int x = 50;
int y = 50;
int width = 100;
int height = 50;
int arcWidth = 20; // 圆角的宽度
int arcHeight = 20; // 圆角的高度
g2d.setColor(Color.BLUE);
g2d.fill(new RoundRectangle2D.Double(x, y, width, height, arcWidth, arcHeight));
}
public static void main(String[] args) {
JFrame frame = new JFrame("圆角矩形示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new RoundedRectangleExample());
frame.setSize(200, 150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
这段示例代码将绘制一个带有圆角的蓝色矩形。您可以根据需要更改颜色,大小和圆角程度。