如何制作JPanel的背景渐变

时间:2012-08-31 18:35:50

标签: java swing jpanel gradient paintcomponent

我想知道如何制作另一个JPanel中的背景渐变。互联网上发现了许多文章,但是所有这些文章都说明了如何覆盖JPanel的paintComponent()而不是如何处理它内部的jPanel。
我使用Netbeans IDE。我创建了一个新的JPanel类,可以覆盖它的paintComponent()。我有另一个jpanel(拖放到父JPanel上)。我想制作它的背景渐变。

以下是我为父母所做的尝试。有效。我怎么能为孩子的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);
        }

1 个答案:

答案 0 :(得分:10)

如果您小心调用super.paintComponent(g),可以直接将渐变添加到面板中,如下所示。

为了实用性,我会抵制尝试使各个组件透明化的诱惑。另请注意,opacity由Look& amp; amp;感觉。

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();
            }
        });
    }
}