JPanel gradient background

34,571

Solution 1

Here you go:

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestPanel extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        int w = getWidth(), h = getHeight();
        Color color1 = Color.RED;
        Color color2 = Color.GREEN;
        GradientPaint gp = new GradientPaint(0, 0, color1, w, h, color2);
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                TestPanel panel = new TestPanel();
                frame.add(panel);
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

Solution 2

You can use this :

JPanel contentPane = new JPanel() {
        @Override
        protected void paintComponent(Graphics grphcs) {
            super.paintComponent(grphcs);
            Graphics2D g2d = (Graphics2D) grphcs;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            GradientPaint gp = new GradientPaint(0, 0,
                    getBackground().brighter().brighter(), 0, getHeight(),
                    getBackground().darker().darker());
            g2d.setPaint(gp);
            g2d.fillRect(0, 0, getWidth(), getHeight()); 

        }

    };

hope that help; you can also back to this artical for more help: Gradient background to any jcomponent

Share:
34,571
Fred
Author by

Fred

Here's the quote I keep close to my heart. In a world of talkers, be a thinker and a doer. Here's some other quotes that I really like, too! "Any code of your own that you haven't looked at for six or more months, might as well have been written by someone else." – Eagleson's Law "Tell me and I forget, teach me and I may remember, involve me and I learn." - Benjamin Franklin

Updated on January 19, 2022

Comments

  • Fred
    Fred over 2 years

    I googled but could find no correct answer. I have a JPanel and I want it to have a gradient that comes from top to bottom. I'm just going to use two colors. How can I achieve this?

  • David Kroukamp
    David Kroukamp over 11 years
    +1 nice example, though Id suggest overriding getPreferredSize() of JPanel and calling pack() on JFrame rather than calling setSize(..)
  • Guillaume Polet
    Guillaume Polet over 11 years
    @DavidKroukamp the setSize() call is meant to have something visible on the screen. I don't want to override getPreferredSize() in this case because my understanding is that the Panel will be later on actually used to set a LayoutManager and add components, therefore, getPreferredSize() should be computed by that LayoutManager and not an arbitrary size. Anyway, this is just nitpicking and I believe that both solutions are acceptable equally.
  • MadProgrammer
    MadProgrammer over 11 years
    I prefer LinearGradientPaint personally, but it depends on the needs ;)
  • Guillaume Polet
    Guillaume Polet over 11 years
    @MadProgrammer Didn't get a chance to look at it yet. Last time I had to set this up was with Java 5, but LinearGradientPaint is only there since 1.6. Thanks for the update.
  • MadProgrammer
    MadProgrammer over 11 years
    @GuillaumePolet I think GradientPaint is faster for two color gradients, LinearGradientPaint just allows for more colors ;)
  • class stacker
    class stacker about 9 years
    I call BS on this. It's good that you're honest enough to link to the source. However, the source has it correct, and you modified it in a wrong way. Hint: JComponent.setOpaque(false); is a key factor and super.paintComponent(grphcs); needs to be the last call. Otherwise, your code will not work with all JComponent objects and also it's not robust regarding any future changes. But thanks for the pointer.
  • class stacker
    class stacker about 9 years
    This code will not work for all JComponent objects. The reference which Mohammed Sayed provides a generic approach by setting the opacity of the original object and painting it as the last action: http://www.javarichclient.com/how-to-add-a-gradient-backgrou‌​nd-to-any-jcomponent‌​/
  • Guillaume Polet
    Guillaume Polet about 9 years
    @ClassStacker Not sure how your comment is relevant to the original question nor why you downvoted this answer.
  • JAVA
    JAVA over 5 years
    @MadProgrammer In the class which extend SynthPainter class i have overridden the method public void paintPanelBackground(SynthContext context, Graphics g, int x, int y, int w, int h) in which i am doing g2.setPaint(new GradientPaint(x, y, Color.DARK_GRAY, 0, h / 2, new java.awt.Color(30, 30, 30))); is it safe performance wise ?
  • MadProgrammer
    MadProgrammer over 5 years
    @JAVA Gradient painting is always expensive, there are cheats, but it requires you to know in which direction the painting will be done (will only really work for horizontal and vertical gradients)