2

I am trying to put a JPanel in the center of a fullscreen JFrame with a defined size, but it's always stretching for the whole screen...

I tried setBounds, setPreferredSize, but they don't work.

This is the code:

public static void showScene(){ //Create the frame to main application. JFrame frame = new JFrame("Application"); // set the title of the frame frame.setExtendedState(JFrame.MAXIMIZED_BOTH); // set the size, maximum size. frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the panel to store the main menu. JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(500,200)); panel.setBackground(new java.awt.Color(0,0,255)); frame.add(panel,BorderLayout.CENTER); } public static void main (String[] args){ showScene(); } 
2
  • If you really want to force the size, then you can set the PreferredSize the minimunSize and the maximumSize. But a better approach would be using a Layout for your JFrame. Commented Mar 12, 2015 at 12:49
  • Override getPreferredSize of the component and return the size you want. Call JFrame#pack to pack the window about the component. You could use a different layout manager, like GridBagLayout which will honour the preferredSize of the components Commented Mar 12, 2015 at 13:01

1 Answer 1

1

BorderLayout stretches the contents to fill the parent container.

If you want the child to have smaller size than the parent, use some other LayoutManager (try FlowLayout).


You can change layout using following code.

Container contentPane = frame.getContentPane(); contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 0,90))); frame.add(panel); frame.pack(); 

For further reference, follow visual guide to layout managers.

Good luck.

Sign up to request clarification or add additional context in comments.

5 Comments

when i change to frame.add(panel,FlowLayout.CENTER), the panel dissapears =/
You need to explicitly set the LayoutManager. Please check the edited answer.
Now, it dissapears again.
Exception in thread "main" java.lang.IllegalArgumentException: illegal component position at java.awt.Container.addImpl(Unknown Source) at java.awt.Container.add(Unknown Source) at javax.swing.JFrame.addImpl(Unknown Source) at java.awt.Container.add(Unknown Source) at gui.showScene(gui.java:32) at gui.main(gui.java:43)
Ok, now i get: Container contentPane = frame.getContentPane(); contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 0,90)); and frame.add(panel); Thanks for the help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.