Как обеспечить визуальное удаление шахматной фигуры с экрана после ее программного удаления в Java Swing?JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Гость
 Как обеспечить визуальное удаление шахматной фигуры с экрана после ее программного удаления в Java Swing?

Сообщение Гость »

Я реализовал шахматную игру с помощью Java Swing, и столкнулся с проблемой: даже после программного удаления шахматной фигуры с доски ее визуальное представление остается на экране. Я проверил, что структура данных, содержащая фрагменты, обновлена ​​правильно, но визуальное представление не отражает это изменение. Как я могу гарантировать, что визуальное представление шахматной фигуры будет удалено с экрана при его программном удалении?

Код: Выделить всё

public static  K getKeyFromValue(Map map, V value) {
for (Map.Entry entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}

public void deleteChessPiece(ChessPiece piece) {
if (piece != null) {
String key = getKeyFromValue(pieceBox, piece);
if (key != null) {
System.out.println(key);
pieceBox.remove(key);
pieceLabels.remove(key);
JLabel label = pieceLabels.get(key);
if (label != null) {
remove(label);
}
}
}
invalidate();
revalidate();
repaint();
}
И:

Код: Выделить всё

package com.wallhack.chess;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JLabel;

public class Board extends JPanel {
private final PieceFactory pieceFactory = new PieceFactory();
public ConcurrentHashMap pieceBox = new ConcurrentHashMap();
public HashMap pieceLabels = new HashMap();
private final int cellSize = 80;
private final int initialX = 63;
private final int initialY = 60;
private final BoardRender boardRender;
private final BoardLayoutManager boardLayoutManager;
private Point highlightCell;

public Board(BoardLayoutManager boardLayoutManager) {
this.boardLayoutManager = boardLayoutManager;
setLayout(new BoardLayoutManager());

boardRender = new BoardRender(initialX, initialY, cellSize);

pieceByDefault();

for (String piece : pieceBox.keySet()) {
createAndPositionLabel(piece);
}

for (String piece : pieceLabels.keySet()) {
JLabel label = pieceLabels.get(piece);
ChessPiece chessPiece = pieceBox.get(piece);
if (label != null && chessPiece != null) {
Point pieceCoordinates = new Point(chessPiece.getCoordinates().x, chessPiece.getCoordinates().y);
add(label , pieceCoordinates);
}
}

MouseHandler mouseHandler = new MouseHandler(this, new PieceMoves(this));
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);

}
public static  K getKeyFromValue(Map map, V value) {
for (Map.Entry entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);

Graphics2D g2 = (Graphics2D) g;
boardRender.drawBoard(g2);
boardRender.drawLabel(g2);

if (highlightCell != null) {
Point cell = gridToPoint(highlightCell);
Rectangle bounds = new Rectangle(cell.x, cell.y, cellSize,cellSize);
g2.setColor(Color.RED);
g2.draw(bounds);
}
}

private void createAndPositionLabel(String piece) {
JLabel label = new JLabel();

try {
String imagePath = "com/wallhack/chess/resources/"  + pieceBox.get(piece).getIndex();
label.setIcon(new ImageIcon(ImageIO.read(Objects.requireNonNull(getClass().getClassLoader().getResource(imagePath)))));

} catch (IOException e) {
e.printStackTrace();
System.out.println("Eroare la citirea imaginii!");
}

Point offset = getBoardOffset();
Point pieceCoordinates = gridToPoint(pieceBox.get(piece).getCoordinates());
label.setBounds(pieceCoordinates.x + offset.x, pieceCoordinates.y + offset.y, cellSize, cellSize);

pieceLabels.put(piece, label);
}

private void pieceByDefault () {
String[][] defaultPositions = {
{"Br1", "Bn1", "Bb1", "Bq", "Bk", "Bb2", "Bn2", "Br2"},
{"Bp1", "Bp2", "Bp3", "Bp4", "Bp5", "Bp6", "Bp7", "Bp8"},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", " ", " ", " "},
{"LP1", "LP2", "LP3", "LP4", "LP5", "LP6", "LP7", "LP8"},
{"LR1", "LN1", "LB1", "LQ", "LK", "LB2", "LN2", "LR2"}
};
for (int i = 0; i < defaultPositions.length; i++) {
for (int j = 0; j < defaultPositions.length; j++) {
String pieceType = defaultPositions[i][j];
if (!pieceType.equals(" ")) {
pieceBox.put(pieceType, pieceFactory.create(pieceType.charAt(1), new Point(j, i)));
}
}
}
}

public Point pointToGrid(Point p) {
Point point = null;
if (p != null) {
var pointX = (p.x - initialX) / cellSize;
var pointY = (p.y - initialY) / cellSize;
if (0  isValidRookMove(coord, initial);
case Queen -> isValidQueenMove(coord, initial);
case King -> isValidKingMove(coord, initial);
};
}
}
Я попытался удалить JLabel, связанный с удаленной шахматной фигурой, из JPanel с помощью метода удаления, но визуальное представление фигуры все равно осталось на экране. Я ожидал, что при удалении JLabel визуальное представление шахматной фигуры также будет удалено с экрана.

Подробнее здесь: https://stackoverflow.com/questions/781 ... fter-delet
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»