How to make the background gradient of a JPanel

Débora picture Débora · Aug 31, 2012 · Viewed 10.5k times · Source

I want to know how to make background gradient which is in another JPanel. Many articles found in internet,but all of them had demostrated how to overide the paintComponent() of the JPanel not how to do for a jPanel which is inside it.
I use Netbeans IDE. I created a new JPanel class and could overide its paintComponent(). I have another jpanel on it (dragged & dropped on to the parent JPanel). I want to make its background gradient.

Here is how I tried for parent. It worked. How can I overide this for child jpanel ?

public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Color color1 = getBackground();
        Color color2 = color1.darker();
        int w = getWidth();
        int h = getHeight(); 
        GradientPaint gp = new GradientPaint(
                0, 0, color1,
                0, h, color2);

        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        }

Answer

trashgod picture trashgod · Aug 31, 2012

If you are careful to invoke super.paintComponent(g), you can add the gradient directly to the panel as shown below.

For usability, I would resist the temptation to try making the individual components transparent. Note also that opacity is controlled by the Look & Feel.

GradientPanel

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
* @see http://stackoverflow.com/q/12220853/230513
*/
public class GradientPanel extends JPanel {

    private static final int N = 32;

    public GradientPanel() {
        this.setBorder(BorderFactory.createEmptyBorder(N, N, N, N));
        this.add(new JLabel("Test:", JLabel.CENTER));
        this.add(new JTextField("This is a test."));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        Color color1 = getBackground();
        Color color2 = color1.darker();
        int w = getWidth();
        int h = getHeight();
        GradientPaint gp = new GradientPaint(
            0, 0, color1, 0, h, color2);
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
    }

    private void display() {
        JFrame f = new JFrame("GradientPanel");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new GradientPanel().display();
            }
        });
    }
}