如何在多个jPanel上绘制GradientPaint?

时间:2011-05-06 00:29:37

标签: java jpanel gradient paint

我有一个jPanel视图对象,并拥有其他jPanel,而jPanel又包含jLabel。我想在对象上绘制一个渐变叠加层,使其外观漂亮,而​​不是枯燥的外观。

到目前为止,我的尝试是:

public class InfoDisplay extends javax.swing.JPanel {


    @Override
     public void paintComponent(Graphics g) {
        UIDefaults uid = UIManager.getDefaults();
        Graphics2D g2d = (Graphics2D)g;

        int w = getWidth();
        int h = getHeight();

        Color lightBlue = new Color(41, 117, 200);
        Color darkBlue = new Color(2, 47, 106);

        if (!isOpaque()) {
            super.paintComponent( g );
            return;
        }

        GradientPaint gp = new GradientPaint(0, 0, lightBlue, 0, h, darkBlue );

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

        setOpaque( false );
        super.paintComponent( g );
        setOpaque( true );
    }
}

这似乎根本不会改变对象背景。我很擅长弄乱那些与Gui默认值无关的东西。

我使用Netbeans中的Gui构建器来创建对象,因此initComponents()也在类中,但我只发布了与该问题相关的源。

也许有人可以指出我正确的方向?

1 个答案:

答案 0 :(得分:4)

如果您想让背景JPanel使用渐变颜料,那么只需使用它即可。不要使用setOpaque和super.paintComponent在代码中做所有有趣的事情。如,

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.*;

@SuppressWarnings("serial")
public class GradientPaintPanel extends JPanel {
   private static final Color LIGHT_BLUE = new Color(41, 117, 200);
   private static final Color DARK_BLUE = new Color(2, 47, 106);

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      GradientPaint gradPaint = new GradientPaint(0, 0, LIGHT_BLUE, 0, getHeight(), DARK_BLUE);
      g2.setPaint(gradPaint);
      g2.fillRect(0, 0, getWidth(), getHeight());
   }

   public GradientPaintPanel() {

   }

   private static void createAndShowUI() {
      GradientPaintPanel gradPaintPanel = new GradientPaintPanel();
      gradPaintPanel.setPreferredSize(new Dimension(400, 300));
      JFrame frame = new JFrame("GradientPaintEg");
      frame.getContentPane().add(gradPaintPanel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}