java JPanel How to fixed sizes

随声附和 提交于 2019-12-10 12:39:22

问题


I want to have a resizable panel, that always has the top green panel of a fixed depth. i.e. all changes in height should effect the yellow panel only.

My code below is almost OK, except the green panel varies in size a little.

How do I do this?

            Panel.setLayout(new BoxLayout(Panel, BoxLayout.Y_AXIS));
        Panel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JPanel TopPanel = new JPanel();
        TopPanel.setPreferredSize(new Dimension(80,150));
        TopPanel.setVisible(true);
        TopPanel.setBackground(Color.GREEN);
        JPanel MainPanel = new JPanel();
        MainPanel.setPreferredSize(new Dimension(80,750));
        MainPanel.setVisible(true);
        MainPanel.setOpaque(true);
        MainPanel.setBackground(Color.YELLOW);

        Panel.add(TopPanel);
        Panel.add(MainPanel);


回答1:


Your question didn't restrict the solution to a BoxLayout, so I am going to suggest a different layout manager.

I would attack this with a BorderLayout and put the green panel in the PAGE_START location. Then put the yellow panel in the CENTER location without a preferredSize call.

http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

Here is an SSCCE example of the solution:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestPad extends JFrame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new BorderLayout());

        JPanel green = new JPanel();
        green.setPreferredSize(new Dimension(80, 150));
        green.setBackground(Color.GREEN);

        JPanel yellow = new JPanel();
        yellow.setBackground(Color.YELLOW);

        frame.getContentPane().add(green, BorderLayout.PAGE_START);
        frame.getContentPane().add(yellow, BorderLayout.CENTER);

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}



回答2:


If you make your Panel use BorderLayout instead of BoxLayout and put TopPanel in BorderLayout.NORTH and MainPanel in BorderLayout.CENTER, then they will both resize horizontally, but only the MainPanel will resize vertically.

See the BorderLayout documentation



来源:https://stackoverflow.com/questions/19936025/java-jpanel-how-to-fixed-sizes

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