Java instanceof

时间:2018-05-14 12:35:15

标签: java instanceof

我有一个节点(Gridpane节点),我想从类中获取instanceof,但无论是节点还是任何对象,我都无法获取我的类的实例,我需要在类中添加一些内容来实现" instanceof& #34;或者我做错了吗?

public void Move(GridPane gridPane) {
    for (Node node : gridPane.getChildren()) {
        if (GridPane.getColumnIndex(node) == this.x && GridPane.getRowIndex(node) == this.y - 2) {
            if (node instanceof blackPawn) {
                gridPane.setRowIndex(node, this.y);
                gridPane.setColumnIndex(node, this.x);
            }
            break;
        }
    }
}

不可转换的类型;不能施放' javafx.scene.Node'至 ' sample.Figures.blackPawn'

blackPawn class

package sample.Figures;

import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

public class blackPawn {
public int x;
public int y;
public ImageView IMG = createChestImage();
private int j = 0;

public blackPawn(){}

public blackPawn(int x,int y)
{
    this.x = x;
    this.y = y;
}

private ImageView createChestImage() {
    final ImageView iv = new ImageView(new Image("sample/Sprites/blackPawn.png"));

    iv.setOnMouseEntered(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            iv.setImage(new Image("sample/Sprites/blackPawnStroke.png"));
            j = 0;
        }
    });

    iv.setOnMouseExited(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if(j == 0)
            iv.setImage(new Image("sample/Sprites/blackPawn.png"));
        }
    });

    iv.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            iv.setImage(new Image("sample/Sprites/blackPawnStroke.png"));
            j = 1;
        }
    });

    return iv;
}

}

2 个答案:

答案 0 :(得分:3)

你正在尝试永远不可能的演员表,编译器不会让你这样做。

例如,

\/

是不允许的,因为String s = "hello"; Integer i = (Integer) s; String不在同一个类层次结构中,因此这种强制转换永远不可能。编译器将允许您这样做:

Integer

但这会在运行时抛出String s = "hello"; Object o = s; Integer i = (Integer) o;

在您的情况下,您可能需要以某种方式从ClassCastException中提取Figure以确定该节点是否有黑色棋子,如

Node

使用方法

if (getFigureForNode(node) instanceof BlackPawn) {
     ...

假设Figure getFigureForNode(Node n) (或BlackPawn extendsimplements

代码嗅觉

请注意,使用Figure通常不是好设计。您可能希望使用方法instanceof,而不是isBlackPawn(Figure f)

答案 1 :(得分:-1)

java instanceof运算符用于测试对象是否是指定类型的实例(类或子类

http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm