为JPanel提供基于百分比的宽度 [英] Giving a JPanel a percentage-based width

查看:135
本文介绍了为JPanel提供基于百分比的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

制作JPanel以宽度占据其父容器固定百分比的最简单方法是什么?

What's the easiest way to make a JPanel that takes up a fixed percentage of its parent container, by width?

其宽度应在其父容器的宽度更改时更新.

Its width should update when that of its parent container changes.

我尝试使用Box.createHorizontalStrut(),但是当JPanel的父容器的宽度更改时,该值不会更新.

I tried using Box.createHorizontalStrut(), but that doesn't update when the width of the JPanel's parent container changes.

推荐答案

您想要的是如何使用?)

使用GridbagLayout可以定义 GridBagConstraints 添加的每个单个组件.

Using a GridbagLayout allows you to define GridBagConstraints for each single component you add.

这些约束包括 weightx 完全符合锡盒上的要求.这是在网格行"中所有组件上计算的相对值,类似于分布零件.

These constraints include weightx which does exactly what it says on the tin. This is a relative value calculated across all components in that "grid-row", similar to distribution parts.

请注意,只有超出组件的首选大小时,weightx才开始起作用.请注意,在设置minimumSize()时,这可能会导致有趣的错误,另请参见此SO答案.

Be aware that the weightx only begins to come into play, when the preferred size of components is exceeded. Be aware that this may lead to interesting bugs, when setting minimumSize(), see also this SO answer.

无论如何:您可以通过指定weightx在当前行中各个组件之间的百分比,或该值的任意倍数,来获得weightx所需的值.

Anyways: you can get the value you need for weightx by specifying it's percentage across the components in it's current row, or any multiple of that.

这意味着要使组件占用可用父容器宽度的50%,请使用weightx = 0.5.确保该行的weightx值总计为1.0

This means for a component to take 50% of the available parent container width, use weightx = 0.5. make sure that the row's weightx values add up to 1.0

这篇关于为JPanel提供基于百分比的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆