简体   繁体   中英

paintComponent executed twice and drawing failure

I'm doing a little personnal project to improve my java skill.

What I do there, is that i create 3 JPanel (a global one, and 2 into the global).

In one of them (the right one), I want to draw blocks. Those blocks have a random height, width and an unique id.

In one of my java class, i create a random number of blocks. Then, I'm doing a function to draw those blocks and here are the problems. First of all, the paintComponent function is executing twice, and I only want it to be executed one time.

Secondly, my blocks are.. not draw very well.. here is a picture of 20 blocks drawing into my panel (to debug, I put a fix number of blocks). My windows is 900x700.

Here is my paintComponent function, I tried to see where I did a mistake, but I pull my hair off..

Your target picture indicates you basically want to render the images in lines, ie if an image wouldn't fit into the current line you'd start a new one. Thus you need to track the offsets for x and y as well as the hight of the highest block in the line. This means for each block you'd do something like this (untested but a little debugging should help if this isn't 100% correct):

//maximum width of a line
int maxWidth = 300;

//Space in pixels between the border as well as the blocks
int paddingX = 5;
int paddingY = 5;

//the offset for the next block
int offsetX = paddingX;
int offsetY = paddingY;

int currentLargestHeight = 0;

for( Block block : blocks ) {
  //if the block doesn't fit into the "line" start a new one
  //we assume an empty line always can take at least one block
  if( block.getWidth() > (maxWidth - offsetX - paddingX) ) {
    //advance down
    offsetY += currentLargestHeight + paddingY;

    //we have a new line so the current largest height is 0 again
    currentLargestHeight = 0;

    //start left again
    offsetX = paddingX;
  }

  //render the block
  g2.fillRect(offsetX, offsetY, block.getWidth(), block.getHeight());

  offsetX += block.getWidth() + paddingX;
  if( block.getHeight() > currentLargestHeight ) {
    currentLargestHeight = block.getHeight();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM