首页 文章

边界和流动布局

提问于
浏览
0

好的,所以今天我的编程练习遇到了一些麻烦 .

练习文本如下:

(使用 FlowLayout 管理器)编写符合以下要求的程序:

  • 创建一个框架并将其布局设置为 FlowLayout

  • 创建两个面板并将它们添加到框架中

  • 每个面板包含三个按钮 . 该小组使用 FlowLayout

按钮应命名为“按钮1”,“按钮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);
    }
}

1 回答

  • 1

    中心区域尽可能多地获得可用空间 . 其他区域的扩展仅为填补所有可用空间所需的数量 .

相关问题