简体   繁体   中英

Java Swing repaint(), revalidate() issue after addind Jpanel to Jpanel

i'm quite new in java and i'm trying create my own scrabble game. I created my own classes Board and Tile both JPanels. while im drawing tiles on my Board :

Tile tile = new Tile(currentlyChosenLetter, jump);
board.add(tile);
tile.setBounds(x * jump + 1, y * jump + 1, jump - 2, jump - 2);

when im doing like this everything seems working fine :

无需重涂

but after adding :

board.revalidate();
board.repaint();

tiles are misplaced, i need to repaint in case of removing Tiles.

WithRepaint

x and y im getting from my mouse position :

int jump = board.getHeight() / 15;
int x = (e.getX() / jump);
int y = (e.getY() / jump);

where e is MouseEvent.

board.revalidate();
board.repaint();

The revalidate() statement invokes the layout manager so the child components are given a size and location based on the rules of the layout manager. The default layout manager for a JPanel is the FlowLayout so the components appear on a single line.

So don't use setBounds(...) . Instead use a proper layout manager like the GridLayout and add components to each square of the grid.

I would suggestion you might want to a JLabel to each grid. Then you can add and Icon to each label with the default icon for a given square. Then as a letter is added you replace the Icon with the text.

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