Disappearing Problems Using a Released MouseEvent In Java

人盡茶涼 提交于 2019-12-06 14:27:48
Hovercraft Full Of Eels

I've looked through some of your code, again there's too much for me to go through in its entirety, but please let me give you some suggestions.

This is brittle/dangerous code:

    JLabel awaitingPiece = (JLabel) c1;
    String tmp1 = awaitingPiece.getIcon().toString();
    if (((tmp1.contains("White")))) {

You're using an object's toString() representation as part of your code logic which is something you should never do. You're also doing String manipulations on the String returned, and again using the returned String for code logic,

    Component c = chessBoard.findComponentAt(e.getX(), e.getY());
    String tmp = chessPiece.getIcon().toString();
    String pieceName = tmp.substring(0, (tmp.length() - 4));
    Boolean validMove = false;

again something that is dangerous to do.

Instead, you could get the Icon and compare for Icon equality via the equals(...) method. Even better though is to get your logic out of your GUI and into the Model section of your program. If you can fully separate concerns, you'll stand a much better chance of having smaller units of code that are much easier to debug for both you and for us.

Otherwise, to get a better more complete answer, you're still going to want to first work to isolate the error, and for that, I still recommend that you use an MCVE.


Also I see that you're checking if an Icon is named "WhitePawn"

    chessPiece.setVisible(false);
    Boolean success = false;
    Component c = chessBoard.findComponentAt(e.getX(), e.getY());
    String tmp = chessPiece.getIcon().toString();
    String pieceName = tmp.substring(0, (tmp.length() - 4));
    Boolean validMove = false;

    //Pawn Moves
    //White Pawn
    if (pieceName.equals("WhitePawn")) {

When in actuality I'll bet that it's named something quite differently. Since your Strings are playing a key role in your program (too great a role, I fear) are you debugging your String values to see why the code doesn't work?

For instance, a few println's could do wonders:

    chessPiece.setVisible(false);
    Boolean success = false;
    Component c = chessBoard.findComponentAt(e.getX(), e.getY());
    String tmp = chessPiece.getIcon().toString();
    String pieceName = tmp.substring(0, (tmp.length() - 4));

    System.out.println("pieceName is: " + pieceName); // ******* Added ********

    Boolean validMove = false;

Myself, I'd not use Strings for this but rather would use enums, something you know will be stable and will be exactly what you assume it to be.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!