So, I’m trying to learn Java Swing and custom components. I’ve created a JFrame, given it a background color, and added a JPanel:
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000, 2000);
frame.setBackground(Color.WHITE);
JPanel jp = new JPanel();
jp.setBackground(Color.BLUE);
jp.setSize(40, 40);
frame.add(jp);
frame.setVisible(true);
The result is a 1000×2000 window colored blue (as opposed to a white window with a 40×40 blue box inside it). Why is the JPanel expanding beyond its specified size?
Using your code, simply add one line to change the
LayoutManagerof theJFrame. Then, when you add the component, it will keep it’s preferred size.Also, instead of calling
jp.setSize(40,40), call jp.setPreferredSize(new Dimension(40,40)).And, you need to call
pack()on theJFrameto tell it to layout its components.Also, you should read up on all of the different
LayoutManagersavailable to you. Here is a great tutorial.