快速提问。我有一个jPanelSquareGrid,在一些正方形中有标签(图像标签,代表棋子)
现在,当我将一个棋子拖放到某个方格时,我想检查一下是否还有棋子。
有没有人知道我如何检查广场内现有物品的jPanelSquareGrid?
提前致谢!
这是我的鼠标事件
public void mousePressed(MouseEvent e)
{
chessPiece = null;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
if (c instanceof JPanel) return;
Point parentLocation = c.getParent().getLocation();
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
chessPiece = (JLabel)c;
chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
layeredPane.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
/*
** Move the chess piece around
*/
public void mouseDragged(MouseEvent me)
{
if (chessPiece == null) return;
// The drag location should be within the bounds of the chess board
int x = me.getX() + xAdjustment;
int xMax = layeredPane.getWidth() - chessPiece.getWidth();
x = Math.min(x, xMax);
x = Math.max(x, 0);
int y = me.getY() + yAdjustment;
int yMax = layeredPane.getHeight() - chessPiece.getHeight();
y = Math.min(y, yMax);
y = Math.max(y, 0);
chessPiece.setLocation(x, y);
}
/*
** Drop the chess piece back onto the chess board
*/
public void mouseReleased(MouseEvent e)
{
layeredPane.setCursor(null);
if (chessPiece == null) return;
// Make sure the chess piece is no longer painted on the layered pane
chessPiece.setVisible(false);
layeredPane.remove(chessPiece);
chessPiece.setVisible(true);
// The drop location should be within the bounds of the chess board
int xMax = layeredPane.getWidth() - chessPiece.getWidth();
int x = Math.min(e.getX(), xMax);
x = Math.max(x, 0);
int yMax = layeredPane.getHeight() - chessPiece.getHeight();
int y = Math.min(e.getY(), yMax);
y = Math.max(y, 0);
Component c = chessBoard.findComponentAt(x, y);
if (c instanceof JLabel)
{
Container parent = c.getParent();
parent.remove(0);
parent.add( chessPiece );
parent.validate();
}
else
{
Container parent = (Container)c;
parent.add( chessPiece );
parent.validate();
}
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
jPanelSquare由这个类组成:
class JPanelSquare extends JPanel {
private int rank;
private int file;
private JLabel chessPiece = null;
public JPanelSquare(int rank, int file, Color bkgrnd) {
this.rank = rank;
this.file = file;
setBackground(bkgrnd);
setLayout(new GridBagLayout());
}
public int getRank() {
return rank;
}
public int getFile() {
return file;
}
@Override
public Component add(Component c) {
chessPiece = (JLabel)c;
return super.add(c);
}
@Override
public void remove(Component comp) {
chessPiece = null;
super.remove(comp);
}
public JLabel getChessPiece() {
return chessPiece;
}
}
答案 0 :(得分:1)
从stackoverflow的某个地方获得了这个类
在我看来,您正在组合来自两个不同来源的代码。
我从我发布的ChessBoard示例中识别出我的拖动代码。
在我的代码中,很容易判断一个棋子是否已经存在,因为代码已经在mouseReleased代码中执行了。方法结尾处的“if语句”是什么。
我不知道你从哪里得到其他代码所以我不能对此发表评论。
我建议你坚持使用一种解决方案。