gpt4 book ai didi

java - 自定义渐变按钮 - 看不到文本

转载 作者:行者123 更新时间:2023-12-01 06:36:30 24 4
gpt4 key购买 nike

我正在制作一个具有渐变效果的自定义按钮。我可以设置渐变效果,但看不到文字。我哪里出错了?

class CustomButton extends JButton {   
Color color1, color2;

public CustomButton(String text, Color color1, Color color2) {
super(text);
this.color1 = color1;
this.color2 = color2;
setOpaque(false);
setSize(new Dimension(450, 350));
setForeground(Color.white);
setText(text);
setContentAreaFilled(false);
}

protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();

GradientPaint paint = new GradientPaint(0, 0, color1, width, height,
color2, true);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Paint oldPaint = g2d.getPaint();
g2d.setPaint(paint);
g2d.fillRect(0, 0, width, height);
g2d.drawString("Button 1", getWidth()/2, 10);
g2d.setPaint(oldPaint);
}
}

注意:我允许用户在运行时更改颜色。根据更改的颜色,我相应地设置了背景。

最佳答案

正如斯坦已经回答的那样,解决方案的一部分是

button.setOpaque(false)

按钮有点疯狂,它们想要挤在一起真的不绘制背景

button.setContentAreaFilled(false)

注意:确切的结果可能仍然高度依赖于 LAF - f.i.看起来很糟糕。对于基于合成器的(例如 Nimbus),您可能会考虑安装一个自定义 Painter,配置了用户选择的渐变/颜色

编辑

刚刚仔细检查:

// tell ui to not paint the background
button.setOpaque(false);
button.setContentAreaFilled(false);

// override paintComponent
protected void paintComponent(...) {
// do custom backgroudn painting
...
// let ui handle the foreground (it wont touch the background due to the false settings above)
super.paintComponent()
}

适用于所有核心 LAF(在 win 上)

关于java - 自定义渐变按钮 - 看不到文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8239394/

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