java - 使用 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);
}
}
解决方案
好的,java.awt.Canvas
默认preferredSize
为0x0
. 因此,当您使用 时gbc.fill = GridBagConstraints.VERTICAL;
,它只会拉伸画布以填充垂直空间,但不会更改宽度(仍然是0
)。
gbc.fill = GridBagConstraints.BOTH;
改为使用
边注...
Swing 使用“轻量级”组件,这些组件在单个图形对等体(或重量级容器)中呈现。这允许 Swing 组件具有“z 排序”(相互重叠/重叠)的概念。
java.awt.Canvas
是一个“重量级”组件,意味着它不支持 z-ordeirng 的概念,因此当您不期望它出现在组件顶部时,您可能会遇到问题。
推荐阅读
- node.js - 如何自定义 nest.js 记录器
- r - 增加轴标题和轴之间的边距
- c# - InfluxDB 2 入门示例不向桶中插入任何数据
- amazon-web-services - 通过 CloudFormation 为 AWS::ApiGateway::Method 创建集成时 ARN 无效
- python - 在 Streamlit 中按下按钮时无法增加值
- python - python中函数的时间复杂度
- django - 在身份验证方法中命名为 url kwargs
- sql - 通过比较日期 SQL 过滤数据
- bit-manipulation - 如果存在相同操作的数学等价物,为什么按位移位的结果不可恢复?
- postgresql - 无法从 PostgresQL 中删除订阅