質問

Okay, so I'm having some trouble with my Programming Exercise today.

The Exercise text goes like this:

(Use the FlowLayout manager) Write a program that meets the following requirements:

  • Create a frame and set its layout to FlowLayout
  • Create two panels and add them to the frame
  • Each panel contains three buttons. The panel uses FlowLayout

The buttons should be named "Button 1", "Button 2" and so on. (i completed the original code)

Now i needed to change my code into BorderLayout while moving 1 panel to south, and the other to the center, i tried but it doesn't seem to come out correctly. The buttons are just on the top and bottom.

Original Code (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);
    }
}

My attempt at the 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);
    }
}
役に立ちましたか?

解決

The center area gets as much of the available space as possible. The other areas expand only as much as necessary to fill all available space.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top