kullalok
kullalok

Reputation: 823

JPanel adding matter

I'm new to adding a JPanel to a JFrame, and I need a little help. In one class I made, I have a large rectangle drawn. This class is a subclass of JPanel. Another class is a subclass of JFrame. When I make a new JPanel object of that class, the rectangle shows up on the frame, but it's ridiculously smaller than usual and it's not in the right position. Here's the code, what's wrong?

    public void gameRender() {

    if( dbImage == null ) {
        dbImage = createImage( dbWIDTH, dbHEIGHT );
        if( dbImage == null )
            return;
    }
    //else
        dbg = dbImage.getGraphics();


    dbg.setColor( Color.white );
    dbg.fillRect( 0, 0, dbWIDTH, dbHEIGHT );
    dbg.setColor( Color.black );

This is part of a method that is constantly called by a while loop earlier in the program (like an animation loop). This is part of the JPanel subclass and this chunk of code is used for double buffering. dbWIDTH is 500 and dbHEIGHT is 400.

This code is from the JFrame subclass that is trying to make an object of the JPanel subclass (the JPanel subclass is called WalkAndJump3).

    wj = new WalkAndJump3();

    Container c = getContentPane();
    c.setLayout( new FlowLayout() );

    c.add( wj );

I tried doing what I did in the JPanel subclass by overriding paintComponent and it didn't work, and I did declar WalkAndJump3 wj as an instance variable so the first line shouldn't be a problem. What's wrong? Again, the problem is that the rectangle drawn is too small and out of place.

Upvotes: 3

Views: 157

Answers (1)

Mikle Garin
Mikle Garin

Reputation: 10153

It is small, because you have FlowLayout (c.setLayout( new FlowLayout() )) as the panel's container (Container c = getContentPane()) layout. This means that all the components you add into that container will align "one by one" (well, in fact it's a flow :) with their minimum sizes as default. In your case - minimum size is almost zero i guess.

There are two options:
1. Not the best one - use setPreferredSize(Dimension) on your JPanel to force its expansion
2. Good one - use proper layout to stretch the panel on whole container size like this:

c.setLayout( new BorderLayout() );

This will help, but i strongly recommend you to read Swing introduction into how layouts work here: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

Upvotes: 3

Related Questions