Reputation: 73
How to make JPanel vertical gradient. I'm using following code but it is horizontal gradient.
myPanel.setUI(new PanelUI() {
public void paint(Graphics g, JComponent c) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(new GradientPaint(new Point(0, 0), Color.white,new Point(1612, 35), Color.black, false));
g2.fillRect(0, 0, 1000, 35);
}
});
Upvotes: 1
Views: 932
Reputation: 11143
From the docs, you're using a constructor that asks you for 2 points and 2 colors:
public GradientPaint(Point2D pt1,
Color color1,
Point2D pt2,
Color color2)
Each point has its own X
and Y
coordinates, so it seems horizontal because you're saying in your code to paint the gradient from the point (0, 0)
to the point (1612, 35)
but actually it's a bit diagonal
In this case, if you want it completely vertical, either change the 1612 on P2 to 0 or change 0 on P1 to 1612
It will fill the shape based on that configuration, I think you're confused thinking it should paint from (0, 0)
to (1612, 35)
with the gradient, but those coords are only for the configuration of the gradient not the actual painting of it
Imagine those coords as a Cartesian map, what happens if you draw a line from (0, 0)
to (10, 10)
? It's a diagonal stroke, now what happens if you draw it from (0, 0)
to (10, 0)
or from (10, 10)
to (20, 10)
? It's a horizontal stroke and what's happens if you draw a line from (0, 0)
to (0, 10)
or from (10, 10)
to (10, 20)
? It's a vertical stroke. See what's the coord changing on each example?
For diagonal strokes both X
and Y
coords change
For horizontal strokes just X
changes
For vertical strokes only Y
changes
So, that's what you need to do :)
Upvotes: 4