gpt4 book ai didi

java - 如何制作JPanel的背景渐变

转载 作者:搜寻专家 更新时间:2023-11-01 01:27:58 26 4
gpt4 key购买 nike

我想知道如何制作另一个 JPanel 中的背景渐变。在互联网上找到很多文章,但它们都演示了如何覆盖 JPanel 的 paintComponent() 而不是如何覆盖其中的 jPanel。
我使用 Netbeans IDE。我创建了一个新的 JPanel 类并可以覆盖它的 paintComponent()。我上面有另一个 jpanel(拖放到父 JPanel 上)。我想制作它的背景渐变。

这是我为 parent 尝试的方式。有效。我怎样才能为 child jpanel 覆盖这个?

public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Color color1 = getBackground();
Color color2 = color1.darker();
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, color1,
0, h, color2);

g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}

最佳答案

如果您小心调用super.paintComponent(g),您可以直接将渐变添加到面板,如下所示。

为了可用性,我会抵制尝试使各个组件透明的诱惑。还要注意 opacity由外观控制。

GradientPanel

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
* @see http://stackoverflow.com/q/12220853/230513
*/
public class GradientPanel extends JPanel {

private static final int N = 32;

public GradientPanel() {
this.setBorder(BorderFactory.createEmptyBorder(N, N, N, N));
this.add(new JLabel("Test:", JLabel.CENTER));
this.add(new JTextField("This is a test."));
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color1 = getBackground();
Color color2 = color1.darker();
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}

private void display() {
JFrame f = new JFrame("GradientPanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
new GradientPanel().display();
}
});
}
}

关于java - 如何制作JPanel的背景渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12220853/

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