首页 > 解决方案 > 使用 GridBagLayout 时没有出现画布

问题描述

我做了一个程序,在屏幕的 2/3 显示视频,在屏幕的 1/3 显示评论,所以我使用了 GridBagLayout;由于某种原因,画布没有出现,但是当我用 JButton 替换它时它可以工作。你能告诉我如何解决这个问题吗?

重要的部分在 Panel 类中,其他代码仅供参考。

最后,我要感谢你帮助我;)

public class Intro extends JFrame{

  Panel panel = new Panel();
  static Canvas canvas;

    public Intro(){
        add(panel);
    }

    public static void receive(Canvas canvas1){
        canvas = canvas1;
    }

    public static void main(String[] args) {
        Intro intro = new Intro();
            intro.setSize(1150, 680);
            intro.setLocationRelativeTo(null);
            intro.setVisible(true);
            intro.setDefaultCloseOperation(EXIT_ON_CLOSE);

        NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),"C:\\Program Files\\VideoLAN\\VLC");
        Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
        MediaPlayerFactory mpf = new MediaPlayerFactory();
        EmbeddedMediaPlayer emp = mpf.newEmbeddedMediaPlayer(new Win32FullScreenStrategy(intro));
        emp.setVideoSurface(mpf.newVideoSurface(canvas));
//        emp.setEnableMouseInputHandling(false);
//        emp.setEnableKeyInputHandling(false);
        emp.prepareMedia("D:\\Crab Rave.mp4");
        emp.play();
    }
}

class Panel extends JPanel{

    JLabel label;

    public Panel(){
      setLayout(new GridBagLayout());

        Canvas canvas = new Canvas();
        canvas.setBackground(Color.BLACK);

        GridBagConstraints gbc = new GridBagConstraints();
          gbc.gridx=0;
          gbc.gridy=0;
          gbc.gridheight=2;
          gbc.fill= GridBagConstraints.VERTICAL;
          gbc.weightx=1;
          gbc.weighty= 1;
          Intro.receive(canvas);
        add(canvas, gbc);

        label = new JLabel("Hi there");
          gbc.gridx=0;
          gbc.gridy=2;
          gbc.gridheight=1;
          gbc.fill= GridBagConstraints.VERTICAL;
          gbc.weightx=1;
          gbc.weighty= 1;
        add(label, gbc);
    }
}

标签: javauser-interface

解决方案


好的,java.awt.Canvas默认preferredSize0x0. 因此,当您使用 时gbc.fill = GridBagConstraints.VERTICAL;,它只会拉伸画布以填充垂直空间,但不会更改宽度(仍然是0)。

gbc.fill = GridBagConstraints.BOTH;改为使用

边注...

Swing 使用“轻量级”组件,这些组件在单个图形对等体(或重量级容器)中呈现。这允许 Swing 组件具有“z 排序”(相互重叠/重叠)的概念。

java.awt.Canvas是一个“重量级”组件,意味着它不支持 z-ordeirng 的概念,因此当您不期望它出现在组件顶部时,您可能会遇到问题。


推荐阅读