java JPanel如何固定大小 [英] java JPanel How to fixed sizes

查看:1779
本文介绍了java JPanel如何固定大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可调整大小的面板,该面板始终具有固定深度的顶部绿色面板.也就是说,所有高度变化都只会影响黄色面板.

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.

我该怎么做?

            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);

推荐答案

您的问题并未将解决方案限制为BoxLayout,因此我将建议使用其他布局管理器.

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

我会用BorderLayout攻击它,并将绿色面板放在PAGE_START位置.然后将黄色面板放在CENTER位置,而无需preferredSize调用.

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

以下是该解决方案的SSCCE示例:

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);
    }
}

这篇关于java JPanel如何固定大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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