Drawing a graphic and placing it inside a panel using a BorderLayout

328 views Asked by At
public MyLayout (){
        frame.setLayout(new BorderLayout());
        panel.setLayout(new BorderLayout());

        panel.add(new GraphicsSurface(),BorderLayout.CENTER);


        frame.add(panel,BorderLayout.NORTH);

        frame.add(btn1,BorderLayout.SOUTH);
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true); 
    }

I'm creating a graphic placing it inside a panel

panel.add(new GraphicsSurface(),BorderLayout.CENTER);

and placing this panel inside a JFrame

frame.add(panel,BorderLayout.NORTH);

Except the graphic is displaying outside the JFrame

JFrame

2

There are 2 answers

1
Paul Samsotha On BEST ANSWER

"I want the Graphic to be displayed centred at the top of the JFrame. I still have more components to ad"

In GraphicsSurface override getPreferredSize and give it the size you want (I guess the size of the clock

class GraphicsSurface extends JPanel {
    @Override
    public Dimension getPreferredSize() {
        return new Dimenstion(..., ...);
    }
}

For panel, don't set the layout. The default FlowLayout will work perfectly (it also centers by default -yeeee!). What will happen is that the GraphicsSurface will maintain its preferred size, as FlowLayout will respect it. Then the panel will be stretched to the width of the frame (the height will remain the GraphicsSurface's height), and the GraphicsSurface will be centered in the panel

With this you should be fine, adding the panel to the frame's NORTH. The center will be left for everything else.

2
Alexxx On

You place your panel at frame NORTH. In north, your panel will take only the widows width. So he has no height (or 1px height).

So try to define a size to your panel:

panel.setPreferedSize(new Dimension(200, 200));

Else, as suggested in comment, place your panel into the CENTER of the frame.

Replace:

frame.add(panel,BorderLayout.NORTH);

by

frame.add(panel,BorderLayout.CENTER);

In center, your panel will get the panel width and height (substract your button height).