如何在Java中单击按钮时在运行时强制转换对象
所以我需要知道如何在运行时将父类强制转换为子类(或者以其他方式指向可用的4种工具之一)。我有一个带有4个工具的绘画程序,这些工具是从我的父工具类“DrawingTool”类中派生出来的。我的类中有一个字段,它扩展了我的“画布”的JPanel以容纳myCurrentTool,该工具需要根据用户当前选择的JToggleButton进行更改。我正在设置它,以便在选择按钮时,我的动作侦听器更改为正确的工具。因此,当某个特定按钮处于活动状态时,paint方法将调用该字段,并且它需要对它应该引用的任何特定子类使用重写的方法。我已经试过myCurrentTool=myTool,不行。我不知道如何在没有编译错误的情况下强制转换它(希望我不知道它的语法) 任何建议都很好。下面是一些代码片段。我的代码分为9个不同的类,所以这与任何地方的代码都不相关如何在Java中单击按钮时在运行时强制转换对象,java,casting,compiler-errors,Java,Casting,Compiler Errors,所以我需要知道如何在运行时将父类强制转换为子类(或者以其他方式指向可用的4种工具之一)。我有一个带有4个工具的绘画程序,这些工具是从我的父工具类“DrawingTool”类中派生出来的。我的类中有一个字段,它扩展了我的“画布”的JPanel以容纳myCurrentTool,该工具需要根据用户当前选择的JToggleButton进行更改。我正在设置它,以便在选择按钮时,我的动作侦听器更改为正确的工具。因此,当某个特定按钮处于活动状态时,paint方法将调用该字段,并且它需要对它应该引用的任何特定子
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));
编辑:
子类可以完全适合父类,但反之亦然。您可能试图将一个不相关的对象放入另一个对象中
原件:
您可能需要重构代码。
如果我理解正确,您希望动态地强制转换到运行时?使用反射非常容易,但我会做得不同:
您只需从DrawingAction获取ID(构造函数中使用的字符串),并将其用作mapmap tools;
中的键
MyClass只是一个接口,其中包含您可能希望在当前事件中通知的方法
例如:
public void onButtonClicked(按钮b,int x,int y);
您根本不需要任何强制转换,使用实现所有接口方法的虚拟抽象类,您只需更改类扩展和方法名称。Swing,
paint()
,paintComponent()
和“单击按钮时”完全不相关。有一种类型转换语法。在您的paintComponent()
方法中有一个例子。您的实际问题是什么?编译器发出的错误消息是什么,它指的是哪一行?1)为了更快地获得更好的帮助,请发布(最小完整可验证示例)。2)始终复制/粘贴错误和异常输出<代码>myDrawingActions在此处输入代码=new ArrayList()代码>很好,这将导致编译器错误。请注意使用代码格式。
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;