Search code examples
javaswingjdialog

Swing Dialog gradient paint Issue


Want to paint gradient background for dialog box


Solution

    1. Don't play with the root pane or layered pane.

    2. Don't override paint() on a JFrame or JDialog.

    If you want to do custom painting for the background then you override the paintComponent(...) method of a JPanel. You then set this panel as the content pane of your dialog.

    Read the section from the Swing tutorial on Custom Painting for working examples to get you started.

    Also, Swing does not support transparent background correctly.

    The basic logic for painting transparent backgrounds is:

    JPanel panel = new JPanel()
    {
        protected void paintComponent(Graphics g)
        {
            g.setColor( getBackground() );
            g.fillRect(0, 0, getWidth(), getHeight());
            super.paintComponent(g);
        }
    };
    panel.setOpaque(false); // background of parent will be painted first
    panel.setBackground( new Color(255, 0, 0, 20) );
    frame.add(panel);
    

    Check out Background With Transparency for more information.

    So first get the gradient painting working on the custom panel using non-transparent colors. Once you understand the proper way to do the custom painting you can then worry about the transparency.