java setBackground 设置红白渐变色
时间: 2024-01-21 14:04:24 浏览: 46
Java 中可以使用 `GradientPaint` 类来创建颜色渐变效果。`GradientPaint` 类提供了一种在两种颜色之间产生渐变的方式,可以用于设置组件的背景颜色。下面是一个设置红白渐变色背景的示例代码:
```java
public class GradientPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int width = getWidth();
int height = getHeight();
Color color1 = Color.WHITE;
Color color2 = Color.RED;
GradientPaint gp = new GradientPaint(0, 0, color1, width, height, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, width, height);
}
}
```
在上面的代码中,我们创建了一个 `GradientPanel` 类,继承自 `JPanel`,重写了 `paintComponent` 方法,在该方法中使用 `GradientPaint` 类创建了红白渐变色的背景,并使用 `g2d.fillRect` 方法将其填充到组件中。可以将该组件添加到 `JFrame` 中,以设置整个窗口的背景颜色。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)