java swing实现圆角方框会自动填充
时间: 2023-09-14 19:03:48 浏览: 102
实现圆角方框并自动填充的步骤如下:
1. 创建一个继承自JPanel的自定义面板类,重写paintComponent方法。
2. 在paintComponent方法中,使用Graphics对象设置圆角矩形的边框和填充颜色。
3. 通过setOpaque方法将自定义面板的不透明度设置为false,这样就可以看到背景颜色。
4. 将自定义面板添加到JFrame中。
下面是一个简单的实现示例:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RoundRectanglePanel extends JPanel {
private Color backgroundColor = Color.WHITE;
private Color borderColor = Color.BLACK;
private int cornerRadius = 10;
public RoundRectanglePanel() {
super();
setOpaque(false);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(backgroundColor);
g2.fillRoundRect(0, 0, getWidth(), getHeight(), cornerRadius, cornerRadius);
g2.setColor(borderColor);
g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, cornerRadius, cornerRadius);
g2.dispose();
}
public void setBackgroundColor(Color backgroundColor) {
this.backgroundColor = backgroundColor;
repaint();
}
public void setBorderColor(Color borderColor) {
this.borderColor = borderColor;
repaint();
}
public void setCornerRadius(int cornerRadius) {
this.cornerRadius = cornerRadius;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Round Rectangle Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
RoundRectanglePanel panel = new RoundRectanglePanel();
panel.setBackgroundColor(Color.YELLOW);
panel.setBorderColor(Color.RED);
panel.setCornerRadius(20);
frame.setContentPane(panel);
frame.setVisible(true);
}
}
```
运行程序,将会看到一个黄色背景、红色边框、圆角半径为20的圆角矩形面板。
阅读全文