当前位置: 代码迷 >> J2SE >> JPanel背景渐变颜色有关问题
  详细解决方案

JPanel背景渐变颜色有关问题

热度:183   发布时间:2016-04-24 02:22:36.0
JPanel背景渐变颜色问题
JPanel top=new JPanel(){ 
private static final long serialVersionUID = 1L; 

protected void paintComponent(Graphics g) { 
Graphics2D g2 = (Graphics2D) g; 
// 绘制渐变 
g2.setPaint(new GradientPaint(0, 0, new Color(116, 149, 226), getWidth(), 
getHeight(), new Color(199, 212, 247))); 
g2.fillRect(0, 0, getWidth(), getHeight()); 
super.paintComponent(g); 

}; 
怎样背景没有渐变颜色,没有颜色,只有一个面板而已.这应怎样改呢.
如果把JPanel改成JLabel则有渐变的颜色.

------解决方案--------------------
再优化一下:

Java code
import java.awt.BorderLayout;import java.awt.Color;import java.awt.GradientPaint;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.LayoutManager;import java.awt.Paint;import javax.swing.JComponent;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.plaf.PanelUI;@SuppressWarnings("serial")public class ColorfulPanel extends JPanel {    private Color color1 = new Color(116, 149, 226);    private Color color2 = new Color(199, 212, 247);    private void init() {        setUI(new PanelUI() {            public void update(Graphics g, JComponent c) {                if (c.isOpaque()) {                    Graphics2D g2 = (Graphics2D) g;                    Paint old = g2.getPaint();                    int w = c.getWidth();                    int h = c.getHeight();                    g2.setPaint(new GradientPaint(0, 0, color1, w, h , color2));                    g2.fillRect(0, 0, w, h);                    g2.setPaint(old);                }                paint(g, c);            }        });    }    public ColorfulPanel() {        super();        init();    }    public ColorfulPanel(Color lt, Color rb) {        super();        if (lt != null) this.color1 = lt;        if (rb != null) this.color2 = rb;        init();    }    public ColorfulPanel(boolean isDoubleBuffered) {        super(isDoubleBuffered);        init();    }    public ColorfulPanel(LayoutManager layout) {        super(layout);        init();    }    public ColorfulPanel(LayoutManager layout, boolean isDoubleBuffered) {        super(layout, isDoubleBuffered);        init();    }    public Color getColor1() {        return this.color1;    }    public void setColor1(Color c) {        if (c != null) this.color1 = c;    }    public Color getColor2() {        return this.color2;    }    public void setColor2(Color c) {        if (c != null) this.color2 = c;    }    public static void main(String[] args) {        JFrame frm = new JFrame("Test");        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        frm.getContentPane().add(new ColorfulPanel(), BorderLayout.CENTER);        frm.setBounds(60, 60, 260, 260);        frm.setVisible(true);    }}