如何使用BoxLayout使组件与JPanel中的TOP对齐? [英] How to make Components align to the TOP in JPanel with BoxLayout?

查看:151
本文介绍了如何使用BoxLayout使组件与JPanel中的TOP对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个名为GalaxyWar的游戏,并且我试图制作一个地图选择菜单。我发现一个问题,当我在具有 setAlignmentX(CENTER_ALIGNMENT)的JPanel上使用具有 BoxLayout.Y_AXIS 的BoxLayout时,分配大小的子组件(JPanel)占据面板的整个高度(全部),而不是分配的高度!

I'm developing a game called GalaxyWar, and I am trying to make a map selection menu. I found a problem that when I am using a BoxLayout with BoxLayout.Y_AXIS on a JPanel with setAlignmentX(CENTER_ALIGNMENT), the subcomponents (JPanel's) with assigned size, take up the entire height of the panel (all together), instead of the assigned height!

这是我的代码:

scrollPane = new JScrollPane();
    scrollPane.setBounds(160, 11, 452, 307);
    add(scrollPane);

    mapContainer = new JPanel();
    mapContainer.setAlignmentX(CENTER_ALIGNMENT);
    mapContainer.setAlignmentY(JPanel.TOP_ALIGNMENT);
    mapContainer.setLayout(new BoxLayout(mapContainer, BoxLayout.Y_AXIS));
    scrollPane.setViewportView(mapContainer);

    JPanel demoPanel = new JPanel();
    demoPanel.setLayout(null);
    demoPanel.setBackground(Color.YELLOW);
    demoPanel.setSize(50, 100);
    mapContainer.add(demoPanel);

我已经对此进行了很长时间的研究,但到目前为止找不到任何解决方案。

I've researched on this for long, but couldn't find any solutions so far.

推荐答案

尝试签出

setPreferredSize() 
setMaximumSize()
setMinimumSize()

设置所有3值相同

如果仍然不起作用,则可以尝试将要设置大小为固定大小的面板放在另一个面板内。

If it still doesn't work, you can try to put the panel, of which you are trying to set the size to fixed, inside another panel.

这篇关于如何使用BoxLayout使组件与JPanel中的TOP对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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