【发布时间】:2014-03-24 20:07:39
【问题描述】:
好的,所以我今天的编程练习有点问题。
练习文本是这样的:
(使用FlowLayout管理器)编写一个满足以下要求的程序:
- 创建一个框架并将其布局设置为 FlowLayout
- 创建两个面板并将它们添加到框架中
- 每个面板包含三个按钮。该面板使用 FlowLayout
按钮应命名为“Button 1”、“Button 2”等。 (我完成了原代码)
现在我需要将我的代码更改为 BorderLayout,同时将 1 个面板向南移动,另一个向中心移动,我尝试了,但它似乎没有正确显示。按钮就在顶部和底部。
原始代码(FlowLayout):
import javax.swing.*;
import java.awt.*;
public class lab5_1 extends JFrame {
public lab5_1() {
setLayout(new FlowLayout());
// Create two panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
// Add three buttons to each panel
panel1.add(new JButton(" Button 1 "));
panel1.add(new JButton(" Button 2 "));
panel1.add(new JButton(" Button 3 "));
panel2.add(new JButton(" Button 4 "));
panel2.add(new JButton(" Button 5 "));
panel2.add(new JButton(" Button 6 "));
// Add panels to frame
add(panel1);
add(panel2);
}
public static void main(String[] args) {
lab5_1 frame = new lab5_1();
frame.setTitle(" Exercise 12_1 ");
frame.setSize(600,75);
frame.setLocationRelativeTo(null); // center frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
我对BorderLayout的尝试:
public class lab5_2 extends JFrame {
public lab5_2() {
setLayout(new BorderLayout());
// Create two panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
// Add three buttons to each panel
panel1.add(new JButton(" Button 1 "));
panel1.add(new JButton(" Button 2 "));
panel1.add(new JButton(" Button 3 "));
panel2.add(new JButton(" Button 4 "));
panel2.add(new JButton(" Button 5 "));
panel2.add(new JButton(" Button 6 "));
//Add Panel to frame
add(panel1, BorderLayout.CENTER);
add(panel2, BorderLayout.SOUTH);
}
public static void main(String[] args) {
lab5_2 frame = new lab5_2();
frame.setTitle(" Exercise 12_2 ");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null); // center frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
【问题讨论】:
-
IMO 因为您没有使用(= 填充)
NORTH或WEST或EAST区域,CENTER区域填充了SOUTH之后剩余的空间(在至少我了解Oracle documentation - BorderLayout 所以)。如果不是这样,您将看到未使用区域的 空白空间。 -
@pasty 所以我的代码是正确的,但展示位置已关闭,因为其余部分未填写?
-
同意糊状。中心部分将扩大以填满所有可用空间。也许展示一张你所期待的和你得到的图片。
-
是的 - 您需要添加更多元素(或移动现有元素)到另一个区域或像这样展示您的解决方案并解释输出。 ;-)
-
@pasty 感谢您的快速回答,只是想确保我的代码没有错(:
标签: java swing border-layout flowlayout