1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Created by IntelliJ IDEA.
* User: bebe
* Date: 10-Jun-2006
* Time: 17:26:43
* To change this template use File | Settings | File Templates.
*/
public class LinearGradientPanel extends JPanel {
private float[] fractions;
private Color[] colors;
public LinearGradientPanel() {
fractions = new float[]{0.0f, 0.3f, 0.5f, 0.7f, 0.9f, 1.0f};
colors = new Color[]{Color.RED, Color.ORANGE, Color.YELLOW, Color.PINK, Color.LIGHT_GRAY, Color.DARK_GRAY};
}
public LinearGradientPanel(float[] fractions, Color[] colors) {
this.fractions = fractions;
this.colors = colors;
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Rectangle bounds = getBounds();
Point2D start = new Point2D.Float(0, 0);
Point2D end = new Point2D.Float(bounds.width, bounds.height);
/**
* start - the gradient axis start Point2D in user space
* end - the gradient axis end Point2D in user space
* fractions - numbers ranging from 0.0 to 1.0 specifying
* the distribution of colors along the gradient
* colors - array of colors corresponding to each fractional value
*/
Paint p = new LinearGradientPaint(start, end, fractions, colors);
g2d.setPaint(p);
g2d.fillRect(0, 0, bounds.width, bounds.height);
}
public static void main(String[] args) {
JPanel myGradientPanel = new LinearGradientPanel(
new float[]{0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1f},
new Color[]{Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.RED, Color.PINK}
);
JFrame myFrame = new JFrame();
myFrame.add(myGradientPanel);
myFrame.setLocationRelativeTo(null);
myFrame.setPreferredSize(new Dimension(400, 300));
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
} |