At my JFrame I’d like to have a dashboard on the right and a custom canvas, where I will draw stuff on the left. The dashboard needs to be fixed width and canvas take the rest. So here is what I do in the JFrame constructor.
getContentPane().setLayout(new BorderLayout());
JPanel leftPanel = new JPanel();
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new FlowLayout());
leftPanel.setLayout(new FlowLayout());
getContentPane().add(BorderLayout.EAST, rightPanel);
getContentPane().add(BorderLayout.CENTER, leftPanel);
rightPanel.add(new JLabel("Label1"));
rightPanel.add(new JLabel("Label2"));
rightPanel.setMaximumSize(new Dimension(100, 200));
leftPanel.add(new CustomCanvas());
pack();
As a result my canvas is squeezed to width 0.
What am I doing wrong?
Unless you add a component to a panel it will have a default size of 0, as you have noticed. When you add it to the left panel which uses a FlowLayout it is displayed at its preferred size and the left panel is resized to fill the space in the Center of the BorderLayout.
So the solution is to add your custom painting panel directly to the Center of the BorderLayout and get rid of the left panel.