日期:2014-05-20 浏览次数:20727 次
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); } }