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
"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.