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(); }
PreferredSizetheminimunSizeand themaximumSize. But a better approach would be using a Layout for your JFrame.getPreferredSizeof the component and return the size you want. CallJFrame#packto pack the window about the component. You could use a different layout manager, likeGridBagLayoutwhich will honour the preferredSize of the components