To change the color of a graphics shape we can use the setPaint()
method. For a simple coloring we can pass the color object into this method, such as Color.RED
or Color.GREEN
.
If you want to paint with a gradient paint you can use the GradientPaint class. This class provides a way to fill a shape with a linear color gradient pattern. To create a gradient color pattern you can pass the following parameter to the object constructor.
x1
: x coordinate of the first specified point in user spacey1
: y coordinate of the first specified point in user spacecolor1
: color at the first specified pointx2
: x coordinate of the second specified point in user spacey2
: y coordinate of the second specified point in user spacecolor2
: color at the second specified point
package org.kodejava.awt.geom;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class GradientPaintDemo extends JComponent {
public static void main(String[] args) {
JFrame frame = new JFrame("Gradient Paint Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new GradientPaintDemo());
frame.pack();
frame.setSize(new Dimension(420, 350));
frame.setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
GradientPaint blackToGray = new GradientPaint(50, 50, Color.BLACK,
300, 100, Color.LIGHT_GRAY);
g2.setPaint(blackToGray);
g2.fill(new Rectangle2D.Double(50, 50, 300, 100));
GradientPaint blueToBlack = new GradientPaint(0, 0, Color.BLUE,
400, 400, Color.BLACK);
g2.setPaint(blueToBlack);
g2.fill(new Rectangle2D.Double(50, 160, 300, 100));
}
}
This code snippet produce the following output:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024