Why is this JPanel not sticking to the specified size?

So, I'm trying to learn Java Swing and custom components. I created a JFrame, given its background color, and added 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);

As a result, a window 1000x2000 in size will be blue (unlike a white window with a blue square 40x40 inside). Why is JPanel expanding for the specified size?

+3
source share
2 answers

Using your code, just add one line to change LayoutManagerinto JFrame. Then, when you add the component, it will save the preferred size.

Also, instead of calling, jp.setSize(40,40)call jp.setPreferredSize (new dimension (40, 40)).

pack() JFrame, .

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);

, LayoutManagers, . - .

+2

JFrame - BorderLayout. , BorderLayout.CENTER . , , .

+2

Source: https://habr.com/ru/post/1768518/


All Articles