Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在JFrame中居中并扩展我的JPanel?_Java_User Interface_Jpanel_Grid Layout - Fatal编程技术网

Java 如何在JFrame中居中并扩展我的JPanel?

Java 如何在JFrame中居中并扩展我的JPanel?,java,user-interface,jpanel,grid-layout,Java,User Interface,Jpanel,Grid Layout,我正在制作一个苹果日历应用程序的副本,我无法将月份名称和年份名称与屏幕中心对齐,同时将左右按钮与屏幕的左右两侧对齐。这是我的密码: 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(thi

我正在制作一个苹果日历应用程序的副本,我无法将月份名称和年份名称与屏幕中心对齐,同时将左右按钮与屏幕的左右两侧对齐。这是我的密码:

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);
但它的表现是这样的:

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

您使用的是
BoxLayout
。BoxLayout只是将组件水平添加到面板中。西、中、东约束仅由
边界布局使用,因此BoxLayout会忽略它们

months.add(monthName, BorderLayout.CENTER);
months.add(year, BorderLayout.CENTER);
使用
BorderLayout
时,只能将单个组件添加到布局的某个区域。因此,如果要将两个组件添加到中心,则需要首先创建一个面板,然后将组件添加到面板中

因此,您的基本代码可能类似于:

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

这几乎100%有效。一切都在正确的位置,除了我的“东”按钮就在我的中心面板旁边。是否有水平胶水或其他东西可以用来修复这个问题?代码对我来说很好。这是一个屏幕截图,我希望右边的按钮一直放在问题的末尾JPanel@JonathanAllenGrant,我没有要照片。我要了一个
SSCCE
,我会的。给我10分钟。