为什么Canvas as contentPane不会绘制添加到JFrame glasspane的不透明组件

时间:2012-11-15 14:02:42

标签: java swing opacity glasspane java-canvas

好的,我有一个Canvas(我正在使用它,因为它可以实现BufferedStrategy)。

我将Canvas添加到我的JFrame contentPane ,然后添加HUDPanel(由{2}组成的JPanel JPanel s - 使用JProgressBar s和JLabel s - 显示健康状况和 chakara 条形图)到我的JFrame s glassPane

HUD上的所有组件都是不透明的。

现在,当我将HUDPanel添加到我的JFrame glassPane 时,Canvas作为 contentPane 2 {{保存组件的1}}不会涂不透明:

enter image description here

但是,如果我向JPanel contentPane 添加JPanel而不是Canvas,那么一切正常:

enter image description here

这是为什么? 我该如何解决?

提前谢谢

HUDPanelTest.java

JFrame

HUDPanel.java

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class HUDPanelTest {

    public HUDPanelTest() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new HUDPanelTest();
            }
        });
    }

    private void initComponents() {
        JFrame frame = new JFrame() {
            @Override
            public Dimension getPreferredSize() {//testing only
                return new Dimension(800, 600);
            }
        };
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        HUDPanel hudPanel = new HUDPanel();
        frame.setGlassPane(hudPanel);
        JPanel p = new JPanel() {
            @Override
            protected void paintComponent(Graphics grphcs) {
                super.paintComponent(grphcs);
                grphcs.setColor(Color.yellow);
                grphcs.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        Canvas c = new Canvas() {
            @Override
            public void paint(Graphics grphcs) {//for testing ONLY I actually use a BufferStrategy
                super.paint(grphcs);

                grphcs.setColor(Color.yellow);
                grphcs.fillRect(0, 0, getWidth(), getHeight());
            }
        };

        frame.add(c);
        //frame.add(p);//this works as expected

        frame.pack();
        frame.setVisible(true);
        hudPanel.setVisible(true);

    }
}

1 个答案:

答案 0 :(得分:2)

  • GlassPane是轻量级的,然后始终位于AWT Canvas之后,

  • 这是JLayeredPaneGlassPane和Java以及3DCAD/CAMOpen GL/Cl的常见问题,这些API基于{ {1}}

  • 同样的问题是使用AWT Containers(轻量级容器),但您可以在JLayer和/或其资源中测试isLightWe....()对等