JPanel adds matter

I am new to adding JPanel to JFrame and I need a little help. In one class I made, I have a large rectangle. This class is a subclass of JPanel. Another class is a JFrame subclass. When I create a new JPanel of this class, the rectangle appears on the frame, but it is ridiculously smaller than usual and is not in the correct position. Here is 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 );

      

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

This code is from a JFrame subclass that tries to create a JPanel subclass (the JPanel subclass is named WalkAndJump3).

    wj = new WalkAndJump3();

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

    c.add( wj );

      

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

+3


source to share


1 answer


This is small because you have a FlowLayout (c.setLayout (new FlowLayout ())) as your container panel layout (Container c = getContentPane ()). This means that all the components you add to this container will align "one after the other" (well, it is actually a stream :) with the default minimum sizes. In your case - the minimum size is almost zero I guess.

There are two options:
1. Not the best - use setPreferredSize (Dimension) on your JPanel to force it to expand
2. Good - use the correct layout to stretch the panel to its full container size like this:



c.setLayout( new BorderLayout() );

      

This will help, but I highly recommend that you read Swing's introduction to how layouts work: http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

+3


source







All Articles