如何根据其内容找出未显示的JPanel的首选大小? [英] How to find out the preferred size of a JPanel which is not displayed, according to its content?

查看:121
本文介绍了如何根据其内容找出未显示的JPanel的首选大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JPanel(内部带有多个标签)在图形上添加动态信息.该面板是动态创建的,在我使用它进行绘制之前是不可见的.

I am using a JPanel (with several labels inside) to add a dynamic information on a graph. This panel is dynamically created, it is not visible before I use it to draw.

为此,我正在使用BufferedImage,并且遵循与其他问题.只要我指定所有尺寸(面板及其组件),它就可以很好地工作.

For this, I am using a BufferedImage, and I follow approximately the same steps as described on this other question. It works good, as long as I specify all sizes (the panel, and its components).

就像在提到的问题的评论中问到的那样,如何确定此面板的最佳尺寸?如果以常规的帧/布局设置显示此面板,则将执行相同的操作.

Like asked as well in comments of the referred question, how can I determine the optimal size of this panel? The same operation would be done if this panel was displayed in a regular frame/layout setting.

就我而言,如何以某种方式包装"此面板,以便将其大小和其内容的大小设置为最佳值(然后由标签的大小确定)?

In my case, how can I "pack", in a way, this panel, so that its size, and size of its content are set to the optimal (determined by the size of labels, then)?

推荐答案

Suraj和willcodejavaforfood使我步入正轨.

Suraj and willcodejavaforfood put me on the good track.

检查pack()方法中实际执行的操作后,我发现这主要是将当前大小设置为getPreferredSize()返回的大小.

Checking what is actually done in a pack() method, I see that this is mostly setting the current size to the one returned by getPreferredSize().

由此,我设法提出了这样的解决方案:

From this, I managed to make such solution:

// Creating the panel
JPanel lPanel = new JPanel();
//lPanel.setSize(1000, 1000); //default size, not needed anymore
lPanel.setLayout(new BoxLayout(lPanel, BoxLayout.PAGE_AXIS));

//Adding the content
lPanel.add(new JLabel("Blah"));
// etc...

//Adjust the panel to its preferred size
lPanel.setSize(lPanel.getPreferredSize());

//Call the layout method 
//(this will adjust the content components to their correct size and position)
lPanel.doLayout();

此方法可以正常工作,并将面板及其内容调整为正确的尺寸(并以一种简单的方式回答我的问题:如何找到所需的尺寸?getPreferredSize()").

This method works correctly, and adjusts the panel and its content to the correct size (and answers my question in a simplistic way: "how to find the preferred size? getPreferredSize()").

但是,它需要将初始大小设置为足够大的大小,以使内容适合或不将其放置在布局上.有点可惜,并不是真正的干净",但是我暂时找不到避免这种情况的方法.

实际上,不需要默认大小,因为getPreferredSize()甚至在调用doLayout()之前都返回正确的值.因此,可以在调用布局方法之前将面板设置为适当的大小.

Actually, the default size was not necessary, because getPreferredSize() returns the correct value, even before calling doLayout(). As such, the panel can be set to its proper size before calling the layout method.

这篇关于如何根据其内容找出未显示的JPanel的首选大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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