Why is this JPanel not sticking to the specified size?
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);
开发者_如何学Python frame.add(jp);
frame.setVisible(true);
The result is a 1000x2000 window colored blue (as opposed to a white window with a 40x40 blue box inside it). Why is the JPanel expanding beyond its specified size?
Using your code, simply add one line to change the LayoutManager
of the JFrame
. 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 the JFrame
to tell it to layout its components.
JFrame frame = new JFrame("Testing");
frame.setLayout(new FlowLayout()); // New line of code
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 2000)); // Modified line of code
frame.setBackground(Color.WHITE);
JPanel jp = new JPanel();
jp.setBackground(Color.BLUE);
jp.setPreferredSize(new Dimension(40, 40)); // Modified line of code
frame.add(jp);
frame.pack(); // added line of code
frame.setVisible(true);
Also, you should read up on all of the different LayoutManagers
available to you. Here is a great tutorial.
The default layout manager for a JFrame
is BorderLayout
. When you add a component to the frame without constraints, it uses BorderLayout.CENTER
as the default constraint. This means the component takes up all available space, regardless of its requested size.
精彩评论