How to make Components align to the TOP in JPanel with BoxLayout?

烈酒焚心 提交于 2019-12-10 21:33:49

问题


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!

Here is my code:

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.


回答1:


try to check out

setPreferredSize() 
setMaximumSize()
setMinimumSize()

set all 3 to the same value.

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.



来源:https://stackoverflow.com/questions/23901234/how-to-make-components-align-to-the-top-in-jpanel-with-boxlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!