Search code examples
javaswinggraphicsflowlayout

Issues with `pack()` and `setLayout()`


I have code

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.Graphics;
import java.awt.FlowLayout;

class GUI extends JFrame {

    JPanel mainPanel;

    public GUI(String header) {

        super(header);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //setLayout(new FlowLayout(FlowLayout.CENTER));

        init();

        add(mainPanel);
        pack();
    }

    public void init() {
        mainPanel = new JPanel(){
            @Override
            public void paintComponent(Graphics g) {
                g.fillOval(0, 0, 50, 50);
            }
        };
    }
}

and in my main method, I have

GUI progam = new GUI("Title");
progam.setLocationRelativeTo(null);
progam.setVisible(true);

If I run the program, I get output:

OUTPUT-1

and if I uncomment the setLayout, I get output:

OUTPUT-2

Two questions:

  1. Why isn't pack() working as expected in the first case? Shouldn't I see the full circle instead of seeing half of it?
  2. Why did the oval turn into a triangle in the second output?

Solution

  • Why isn't pack() working as expected in the first case? Shouldn't I see the full circle instead of seeing half of it?

    It is, your mainPanel is providing no sizing hints for the layout manager to work with, so it's using it's component's default sizing hints (0x0)

    Add

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(50, 50);
    }
    

    to you mainPanel and super.paintComponent(g) to your paintComponent method, before you do any custom painting

    Why did the oval turn into a triangle in the second output?

    That would be the difference between BorderLayout and FlowLayout