简体   繁体   English

如何在JFrame中居中和扩展JPanel?

[英]How can I center and widen out my JPanel in my JFrame?

I am making a copy of the apple calendar application, and I am having trouble aligning the month name and year name with the center of my screen, while aligning the left and right buttons with the left and right sides of the screen. 我正在制作苹果日历应用程序的副本,在将月份名称和年份名称与屏幕中心对齐,同时将左右按钮与屏幕左侧和右侧对齐时遇到麻烦。 Here is my code: 这是我的代码:

final JPanel months = new JPanel();
months.setLayout(new BoxLayout(months,BoxLayout.X_AXIS));
months.add(back, BorderLayout.WEST); //back is a JButton
JLabel monthName = new JLabel(this.monthNames[this.month]+" ", SwingConstants.CENTER); 
JLabel year = new JLabel("" + this.year, SwingConstants.CENTER);
monthName.setFont(new Font("Helvetica", 0, 24));
year.setFont(new Font("Helvetica", 0, 24));
monthName.setHorizontalAlignment(JLabel.CENTER);
months.add(monthName, BorderLayout.CENTER);
months.add(year, BorderLayout.CENTER);
months.add(front, BorderLayout.EAST);
add(months);

Yet it shows up like this: 但是它显示如下:

http://i.stack.imgur.com/RasfN.png

months.setLayout(new BoxLayout(months,BoxLayout.X_AXIS));

You are using a BoxLayout . 您正在使用BoxLayout A BoxLayout just adds the components horizontally to the panel. BoxLayout只是将组件水平添加到面板中。 The WEST, CENTER, EAST constrains are only used by a BorderLayout so they are ignored by the BoxLayout. WEST,CENTER,EAST约束仅由BorderLayout使用,因此BoxLayout将忽略它们。

months.add(monthName, BorderLayout.CENTER);
months.add(year, BorderLayout.CENTER);

When using a BorderLayout you can only add a single component to a region of the layout. 使用BorderLayout ,只能将单个组件添加到布局的区域。 So if you want to add two components to the CENTER you need to first create a panel and add the components to the panel. 因此,如果要向CENTER添加两个组件,则需要首先创建一个面板并将这些组件添加到面板。

So your basic code might be something like: 因此,您的基本代码可能类似于:

JPanel centerPanel = new JPanel();
centerPanel.add(month);
centerPanel.add(year);

JPanel mainPanel = new JPanel( new BorderLayout() );
mainPanel.add(westButton, BorderLayout.WEST);
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(eastButton, BorderLayout.EAST);

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

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