我有一个
JPanel
,我想在它里面绘制一个渐变。我已经有了下面的代码,但是这只绘制了一个由两种颜色组成的渐变。我想添加第三种颜色,但不知道该怎么做。我想要的是将面板的左上角涂成白色,右上角涂成红色,两个底角都涂成黑色。要实现这个目标,我应该做些什么呢?类似这样的效果:package pocketshop.util;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class ColorPicker extends JPanel{
public ColorPicker(){
repaint();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, Color.white,
0, h, Color.black);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
}
编辑:可能的解决方案
我能想到的方法是使用两个渐变,一个水平的,一个垂直的,就像这样:
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
// Vertical
GradientPaint gp = new GradientPaint(
0, 0, new Color(0,0,0,0),
0, h, Color.black);
// Horizontal
GradientPaint gp2 = new GradientPaint(
0, 0, Color.white,
w, 0, Color.red, true);
g2d.setPaint(gp2);
g2d.fillRect(0, 0, w, h);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}