将按钮添加到半透明JPanel时的Java渲染工件

时间:2019-03-17 21:53:59

标签: java swing user-interface jframe jcomponent

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

呈现此警报时,会出现伪像:最初选择的按钮上没有呈现警报背景。在按钮上移动鼠标时,似乎无缘无故地在两个位置绘制了按钮的文本。

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

Initial artifact

Moving mouse around

导致这些问题的代码:

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 个答案:

没有答案