java jpanel 半透明_向半透明JPanel添加按钮时的Java呈现工件

在尝试创建一个具有半透明背景(70%不透明度的白色)和圆角的自定义JPanel组件时,作者遇到一个问题:当在JPanel上添加按钮时,初始渲染时不显示背景,且按钮文本在鼠标移动时显得绘制在两个位置。代码示例展示了如何创建这个组件,包括按钮设置和背景填充。寻求解决方案以修复渲染问题。
摘要由CSDN通过智能技术生成

我有个问题。我正在尝试创建一个可以在JFrame中显示的“alert”组件。此警报有半透明背景(70%不透明,白色),背景上有少量的J按钮。背景本身有圆角,因此我制作了一个自定义组件。

呈现此警报时,将显示项目:最初选定的按钮上不会呈现警报背景。当我在按钮上移动鼠标时,看起来按钮的文本无缘无故地被画在两个地方。

工件的屏幕截图(顶部=初始渲染,底部=移动鼠标):

fFqQU.png

aHQMP.png

导致这些问题的代码:

public class Test {

public static void main(String[] args) {

MyRoundedTransparentBackground background = new MyRoundedTransparentBackground();

background.setSize(200, 200);

background.setLocation(100, 100);

background.setLayout(new GridBagLayout());

JPanel spacer = new JPanel();

spacer.setBackground(new Color(0, 0, 0, 0));

GridBagConstraints c = new GridBagConstraints();

c.gridwidth = 1;

c.gridheight = 1;

c.weighty = 1;

background.add(spacer, c);

JButton button1 = new JButton("Hi there");

JButton button2 = new JButton("Bye ...");

button1.setBackground(new Color(0, 0, 0, 0));

button1.setFocusPainted(false);

button1.setBorderPainted(false);

button2.setBackground(new Color(0, 0, 0, 0));

button2.setFocusPainted(false);

button2.setBorderPainted(false);

c.weighty = 0;

c.gridy = 1;

background.add(button1, c);

c.gridx = 1;

background.add(button2, c);

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(600, 600);

frame.setLocation(2000, 100);

frame.setLayout(null);

frame.getContentPane().setBackground(Color.red);

frame.add(background);

frame.setVisible(true);

}

private static class MyRoundedTransparentBackground extends JComponent {

@Override

public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2 = (Graphics2D) g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

g2.setColor(new Color(1f, 1f, 1f, 0.7f));

g2.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);

}

}

有人能帮我找出问题所在,并给出一个潜在的解决方案,以实现期望的行为吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值