java jpanel 大小,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.

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

geXv2.jpg

解决方案

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.

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值