如何在多个 jPanel 上进行 GradientPaint?
我有一个视图对象,它是一个 jPanel,并包含其他 jPanel,而其他 jPanel 又包含 jLabels。我想在对象上绘制渐变叠加层,使其具有漂亮的时尚外观,而不是无聊的朴素外观。
到目前为止我的尝试是:
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() 也在类中,但我仅发布了与问题相关的源代码。
也许有人可以指出我正确的方向?
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 give 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望背景 JPanel 使用渐变绘画,那么只需使用它即可。不要在代码中使用 setOpaque 和 super.paintComponent 做那些有趣的事情。例如,
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.,