【发布时间】:2012-12-07 21:52:13
【问题描述】:
我有一个JPanel,我想在其中绘制一个渐变。我有下面的代码,但只绘制了 2 色渐变。我想添加第三个,但不知道如何。我想要的是让面板的左上角为白色,右上角为红色,两个底角为黑色。我必须做些什么来实现这一点,看起来像这样:
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);
}
}
编辑:可能的解决方案
我能够想出使用 2 种渐变,一种是水平的,一种是垂直的,如下所示:
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);
}
【问题讨论】: