Java AWT Graphics2D set linear gradient paint
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.LinearGradientPaint; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel { Random rnd = new Random(); @Override/* www . j a va2 s. c om*/ public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight()); // antialising g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //Rectangle2D Rectangle2D rectangle = new Rectangle2D.Float(50, 50, 100, 70); float[] dists2 = { .1f, 1.0f}; Color[] colors2 = {new Color(255, 200, 0, 200), new Color(0, 0, 0, 200)}; LinearGradientPaint gradient2 = new LinearGradientPaint(100, 50, 100, 150, dists2, colors2); g2d.setPaint(gradient2); g2d.fill(rectangle); } public static void main(String[] args) { // create frame for Main JFrame frame = new JFrame("java2s.com"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main Main = new Main(); frame.add(Main); frame.setSize(300, 210); frame.setVisible(true); } }