固定宽度,JPanel中可变高度,带流量 [英] Fixed width, variable height in JPanel with flow

查看:179
本文介绍了固定宽度,JPanel中可变高度,带流量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java的布局管理器有一个烦人的问题.我有以下情况:在面板 A 中是另外两个具有绝对布局的面板 B 和具有FlowLayout的 C . B 高度定制,并通过setPreferredSize设置了固定大小. C fixed 宽度应与 B 相同,但其高度可变,这取决于流中添加了多少个组件.然后,生成的 A 应该具有固定的宽度和A.height + B.height作为高度–至少这是我想要的.

I have an annoying problem with Java’s layout managers. I have the following situation: In a panel A are two other panels B with an absolute layout and C with a FlowLayout. B is highly customized and has a fixed size set via setPreferredSize. C should have the same fixed width as B but otherwise be of a variable height, depending on how many components are added in the flow. The resulting A should then have the fixed width and A.height + B.height as the height – at least that is what I want.

但是我得到的是面板 A 的宽度根本没有固定(即使我设置了它的首选大小),面板 C 中的内容也没有固定不会自动换行,而是以长行显示.当然,这也会使 B 的宽度大于应有的宽度.

However what I get is that the width of the panel A is not fixed at all (even if I set its preferred size), and the contents in panel C are not automatically wrapping but instead are displayed in a long line. Of course this also makes B having a larger width than it should be.

该如何解决?有没有更好的布局,还是我必须使用绝对布局来模拟所有布局?

What can I do to fix that? Is there any better layout, or do I have to emulate that all using an absolute layout?

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;

public class Test extends JPanel
{
    public Test ()
    {
        this.setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) );

        JPanel top = new JPanel( null );
        top.setBackground( Color.GREEN );
        top.setPreferredSize( new Dimension( 200, 20 ) );
        JPanel flowPanel = new JPanel( new FlowLayout( FlowLayout.LEFT, 2, 2 ) );

        this.add( top );
        this.add( flowPanel );

        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
        flowPanel.add( new JButton( "x" ) );
    }
}

推荐答案

包装布局应该会有所帮助.

这篇关于固定宽度,JPanel中可变高度,带流量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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