4

我知道之前发布过类似的问题,但没有答案或示例代码。

我需要在画布上放置一个透明的 JPanel。下面发布的代码不起作用

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class Main {
    private static class Background extends Canvas{
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.setColor(Color.RED);
            g.drawOval(10, 10, 20, 20);
        }
    }

    private static class Transparent extends JPanel {

        public Transparent() {
            setOpaque(false);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.GREEN);
            g.drawOval(20, 20, 20, 20);
        }
    }

    public static void main(String[] args){
        JFrame frame = new JFrame();
        JLayeredPane layered = new JLayeredPane();
        Background b = new Background();
        Transparent t = new Transparent();

        layered.setSize(200, 200);
        b.setSize(200, 200);
        t.setSize(200, 200);

        layered.setLayout(new BorderLayout());
        layered.add(b, BorderLayout.CENTER, 1);
        layered.add(t, BorderLayout.CENTER, 0);

        frame.setLayout(new BorderLayout());
        frame.add(layered, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setVisible(true);
    }
}

使用整个框架的 GlassPane 属性是最后的解决方案(强烈建议不要这样做)

4

2 回答 2

2

您可能无法使其工作,因为您将重量级和轻量级组件混合在一起。

过去,在 Canvas 等重量级组件上绘制轻量级面板是不可能的。由于 JDK 6 Update 12 和 JDK 7 build 19 Java 已经纠正了这个问题,您可以正确地重叠 2,但是它有一些限制。特别是在您的情况下,重叠摆动组件不能是透明的。

A good description for this including the newer behaviour can be found on this page: Mixing Heavyweight and Lightweight Components Check the limitations section for your specific problem.

I don't think using the GlassPane will help as it is also lightweight.

If you change the BackGround class to extend JPanel instead of Canvas you will get the behaviour you want.

于 2011-01-21T16:54:33.093 回答
0

While AWT is limited it should not be too hard to implement something similar with AWT itself by extending either the Container or Component class.

于 2011-01-21T18:28:21.663 回答