简体   繁体   English

将Jpanel添加到Jpanel后,Java Swing repaint(),revalidate()问题

[英]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. 我是Java的新手,我正在尝试创建自己的拼字游戏。 I created my own classes Board and Tile both JPanels. 我创建了自己的类Board和Tile两个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 : x和y im从我的鼠标位置获取:

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

where e is MouseEvent. 其中e是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. revalidate()语句将调用布局管理器,以便根据布局管理器的规则为子组件指定大小和位置。 The default layout manager for a JPanel is the FlowLayout so the components appear on a single line. JPanel的默认布局管理器是FlowLayout因此组件显示在一行上。

So don't use setBounds(...) . 所以不要使用setBounds(...) Instead use a proper layout manager like the GridLayout and add components to each square of the grid. 而是使用像GridLayout这样的适当的布局管理器,并将组件添加到网格的每个正方形。

I would suggestion you might want to a JLabel to each grid. 我建议您可能要对每个网格使用JLabel Then you can add and Icon to each label with the default icon for a given square. 然后,您可以使用给定正方形的默认图标向每个标签添加和Icon Then as a letter is added you replace the Icon with the text. 然后,在添加字母后,用文本替换图标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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