gpt4 book ai didi

java - 如何在多个 jPanel 上进行 GradientPaint?

转载 作者:行者123 更新时间:2023-12-01 19:17:38 24 4
gpt4 key购买 nike

我有一个 View 对象,它是一个 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() 也在类中,但我只发布了与问题相关的源代码。

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

最佳答案

如果您希望背景 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();
}
});
}
}

关于java - 如何在多个 jPanel 上进行 GradientPaint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5905595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com