JPanel not working with setSize & setPrefferedSize
java, jpanel, swing
Solution
The problem is, `JFrame` uses a `BorderLayout`, which will try and size the content to fit the parent container. While `BorderLayout` will try and use the preferred size as a hint, if the available space is greater or less then, it will automatically adjust to allow the center content (the default position) to fill the entire available space of the parent container.
You could try using a `FlowLayout` or `GridBagLayout` which is more likely to honour the preferred size in more situations
Take a look at How to layout components on containers for more details
Problem
Please explain why it does not work, also could you post a solution to solve this issue. Thank you very mucho in advance. ``` public class Run extends JFrame{ /** Fields **/ static JPanel jpanel; private int x, y; /** Constructor **/ public Run() { /** Create & Initialise Things **/ jpanel = new JPanel(); x = 400; y = 400; /** JPanel Properties **/ jpanel.setBackground(Color.red); jpanel.setPreferredSize(new Dimension(20, 30)); /** Add things to JFrame and JPanel **/ add(jpanel); /** JFrame Properties **/ setTitle("Snake Game"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setCursor(null); setResizable(false); setSize(new Dimension(x,y)); setLocationRelativeTo(null); setVisible(true); } /** Set the Cursor **/ public void setCursor() { setCursor (Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } /** Main Method **/ public static void main(String [ ] args) { Run run = new Run(); run.setCursor(); } } ```