I have a view object that is a jPanel and holds other jPanels which in turn hold jLabels. I'm wanting to paint a gradient overlay on the object to g开发者_JS百科ive it a nice sleek look rather than the boring plain look.
My attempt thus far is:
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 );
}
}
This doesn't seem to change the objects background at all. I'm fairly new to messing with things that aren't related to the Gui defaults.
I used the Gui builder in Netbeans to create the object, so initComponents() is also in the class, but I posted only the source that is relevant to the question.
Perhaps someone can point me in the right direction?
If you want a background JPanel to use a gradient paint, then just use it. Don't do all that funny stuff in your code with setOpaque and super.paintComponent. e.g.,
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();
}
});
}
}
精彩评论