单击按钮时如何在Java中在运行时强制转换Object

时间:2014-11-16 09:14:08

标签: java casting compiler-errors

所以我需要知道如何在运行时将子类强制转换为子类(或者指向可用的4种工具之一的其他方式)。我有一个带有4个工具的绘图程序,这些工具是从我的父工具类“DrawingTool”类中继承而来的。我的班级中有一个字段,它将JPanel扩展为我的“画布”以保存myCurrentTool,需要根据用户当前选择的JToggleButton进行更改。我正在设置它,所以当选择按钮时,我的动作监听器会更改为正确的工具。因此,当一个特定的按钮处于活动状态时,paint方法将调用该字段,并且它需要使用重写的方法来处理它应该引用的任何特定子类。我试过myCurrentTool = myTool,没有去。无法弄清楚如何在没有编译错误的情况下进行转换(希望我只是不知道这个的语法。

任何建议都会很棒。这是一些代码片段。我的代码分为9个不同的类,所以这里几乎没有相关的块。

public DrawingAction(final String theName, final Icon theIcon,
                      final DrawingTool theTool, final int theKey) {
    super(theName, theIcon);
    putValue(Action.SHORT_DESCRIPTION, theName + " background");
    putValue(Action.SELECTED_KEY, true);
    putValue(Action.MNEMONIC_KEY, theKey);
    myTool = theTool;

}

...
     myDrawingActions `enter code here`= new ArrayList<DrawingAction>();
            myDrawingActions.add(new DrawingAction("Pencil", new ImageIcon("icons\\pencil.gif"),
                                                   new PencilTool(), KeyEvent.VK_L));
            myDrawingActions.add(new DrawingAction("Line", new ImageIcon("icons\\line.gif"),
                                                   new LineTool(), KeyEvent.VK_L));
            myDrawingActions.add(new DrawingAction("Rectangle",
                                                   new ImageIcon("icons\\rectangle.gif"),
                                                   new RectangleTool(), KeyEvent.VK_R));
            myDrawingActions.add(new DrawingAction("Ellipse", new ImageIcon("icons\\ellipse.gif"),
                                                   new EllipseTool(), KeyEvent.VK_E));

...

public void paintComponent(final Graphics theGraphics) {
    super.paintComponent(theGraphics);
    final Graphics2D g2 = (Graphics2D) theGraphics;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                         RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setStroke(new BasicStroke(myLineThickness));
    g2.setColor(myColor);
    g2.draw(myCurrentTool.draw());
}

...

/**
 * Instance of the Line Drawing Tool.
 */
private LineTool myLine;

/**
 * Instance of Rectangle Tool.
 */
private RectangleTool myRectangle;

/**
 * Instance of Ellipse Tool.
 */
private EllipseTool myEllipse;

/**
 * Instance of Pencil Tool.
 */
private PencilTool myPencil;

/**
 * Holds the currently selected tool.
 */
private DrawingTool myCurrentTool;

1 个答案:

答案 0 :(得分:1)

修改

子类可以完全适合父类,但反之则不然。您可能正在尝试将不相关的对象放入另一个对象中。

<强>原始

您可能希望重构代码。 如果我理解正确,你想动态地转换为运行时?这很容易使用反射,但我会不同地做:

您只需从DrawingAction获取ID(您在构造函数中使用的String),并将它们用作地图Map<String, MyClass> tools;中的Key。

MyClass只是您可能想要通知当前事件的方法接口。

例如:

public void onButtonClicked(Button b, int x, int y);

您不需要任何这样的转换,使用实现所有接口方法的虚拟抽象类,您可能只需更改类扩展和方法名称。