简体   繁体   English

如何在Java中更改面板的大小?

[英]How can I change the size of a Panel in Java?

I'm trying to create a simple login screen consisting of different panels. 我正在尝试创建一个由不同面板组成的简单登录屏幕。 I want help in resizing panels. 我需要调整面板大小的帮助。 The Panel I want resized is coloured in Green. 我要调整大小的面板为绿色。 I want to make it a bit smaller. 我想缩小一点。 The Panel in Green is the North Panel and is set to Border Layout. 绿色的面板是北面板,设置为边框布局。 I want to make the green panel smaller since i feel its too big 我想使绿色面板变小,因为我感觉它太大了

I tried northPanel.setSize(150,150); 我尝试了northPanel.setSize(150,150); but I got no result 但我没有结果

This is my code: 这是我的代码:

JLabel lblWelcome = new JLabel("Welcome To The Login Screen", SwingConstants.CENTER);
JPanel northPanel = new JPanel(new BorderLayout());
northPanel.setBackground(Color.green);
northPanel.add(lblWelcome, BorderLayout.CENTER);

登录屏幕

You are using a BorderLayout which has five positions to put components in the layout. 您使用的BorderLayout具有五个位置,可将组件放置在布局中。 The five positions are PAGE_START, PAGE_END, LINE_START, LINE_END, and CENTER. 这五个位置是PAGE_START,PAGE_END,LINE_START,LINE_END和CENTER。 Here is a diagram of these positions: 这是这些位置的图表:

在此处输入图片说明

For this layout, you want to put the component that should take the remaining space of the frame in the CENTER position. 对于此布局,您想将应该占用框架剩余空间的组件放在CENTER位置。 For this reason, the northPanel is probably better suited in the PAGE_START position while the JPanel that houses the login labels and submit button should be in the CENTER position. 因此,northPanel可能更适合PAGE_START位置,而包含登录标签和Submit按钮的JPanel应该位于CENTER位置。 Using this positioning will allow you to resize the northPanel and allow the panel housing the login labels and submit button to take up the remaining frame space. 使用此定位将允许您调整northPanel的大小,并允许包含登录标签和Submit按钮的面板占用剩余的框架空间。

I want to make the green panel smaller 我想缩小绿色面板

Looks to me like the two panels are the same size which tells me you are using a GridLayout for your frame. 在我看来,这两个面板的尺寸相同,这告诉我您正在为框架使用GridLayout

Don't use a GridLayout, instead keep the default BorderLayout of the frame. 不要使用GridLayout,而是保留框架的默认BorderLayout。

Then your code would be something like: 那么您的代码将类似于:

JLabel lblWelcome = new JLabel("Welcome To The Login Screen", SwingConstants.CENTER);
JPanel northPanel = new JPanel(new BorderLayout());
northPanel.setBackground(Color.green);
northPanel.add(lblWelcome, BorderLayout.CENTER);

frame.add(northPanel, BorderLayout.PAGE_START);
frame.add(centerPanel, BorderLayout.CENTER);

Now the green panel will only be as big as the JLabel. 现在,绿色面板将仅与JLabel一样大。 If you want the panel to be bigger, then add an EmptyBorder to the northPanel. 如果您希望面板更大,则将一个EmptyBorder添加到northPanel。 Read the section from the Swing tutorial on How to Use Borders for more information. 阅读Swing教程中有关如何使用边框的部分, 获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM