Search code examples
javabuttonpanelframeflowlayout

Create a frame using FlowLayout


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 think I'm having some trouble with adding the panels to the frame because when i run the program, it shows an empty frame.

Here is the code i have.

import javax.swing.*;
import java.awt.*;

public class Exercise12_1 extends JFrame {

    public Exercise12_1() {
        setLayout(new FlowLayout());

        JFrame frame = new JFrame(" Exercise 12_1 ");
        frame.setLayout(new FlowLayout());

        // Create two panels
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();

        panel1.setLayout(new FlowLayout());
        panel2.setLayout(new FlowLayout());

        // 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
        frame.add(panel1);
        frame.add(panel2);
    }

    public static void main(String[] args) {
        Exercise12_1 frame = new Exercise12_1();
        frame.setTitle(" Exercise 12_1 ");
        frame.setSize(600, 100);
        frame.setLocationRelativeTo(null); // center frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

I would greatly appreciate it if some of you took your time to help me out here. Thanks.


Solution

  • Your main method creates a frame:

    Exercise12_1 frame = new Exercise12_1();
    

    and then makes it visible.

    And the constructor of this 'Exercise12_1' frame creates another frame, and adds panel to this other frame:

    JFrame frame = new JFrame(" Exercise 12_1 ");
    frame.setLayout(new FlowLayout());
    

    The constructor shouldn't create another frame. It should add the panels to this: the frame being constructed, and that will then be made visible.

    Also, you should not use setSize(), but pack(), to make the frame have the most appropriate size based on the preferred size of all the components it contains.