views:

41

answers:

2

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 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?

+2  A: 

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.

Ash
try using a GridBagLayout LayoutManager to get your desired results
RD
+2  A: 

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.

jjnguy
@Justin: When I run this the frame has 0 height. (Also, possible typo: FlowLatout = FlowLayout?)
Ash
@Ash, yeah....my bad. Typos, and I forgot 2 modifications. Added pack, and, also need to change the second set size call.
jjnguy
@Ash, please try the new version.
jjnguy
@Justin: Yep, looks good.
Ash
@Ash, thanks. Sometimes I'm not as good of a compiler or JVM as I think I am.
jjnguy