问题:有没有办法从FocusInEvent
实例FocuseEvent
?因为我有几个这样的事件。(例如来自MouseEvent的MouseClickedEvent,来自KeyEvent的KeyPressedEvent)
子类如:
interface SwingExtendEvent
{}
class FocusInEvent extends FocusEvent implements SwingExtendEvent
{
public FocusInEvent(Component source, int id, boolean temporary,
Component opposite)
{
super(source, id, temporary, opposite);
}
}
class FocusOutEvent extends FocusEvent implements SwingExtendEvent
{
public FocusOutEvent(Component source, int id, boolean temporary,
Component opposite)
{
super(source, id, temporary, opposite);
}
}
我的解决方案:
public static <T extends FocusEvent & SwingExtendEvent> T event(Class<T> eventClass, FocusEvent e)
{
Constructor<T> constructor;
T o = null;
try
{
// Constructor
// (Component source, int id, boolean temporary,
// Component opposite)
constructor = eventClass.getConstructor(Component.class, int.class,boolean.class,
Component.class);
o = (T) constructor.newInstance(
e.getComponent(), e.getID(), e.isTemporary()
, e.getOppositeComponent());
} catch(Exception ex)
{
// 这里不应该出现异常 因为 实现的 类 都必须实现该构造函数
ex.printStackTrace();
}
return o;
}
修改
我正在编写一个Swing事件适配器。一个侦听器处理所有事件,然后发布到一个guava EventBus。
我的听众的一部分
@Override
public void mouseWheelMoved(MouseWheelEvent e)
{
Events.trigger( emitter, e);
}
@Override
public void mouseDragged(MouseEvent e)
{
Events.trigger( emitter, SwingEvents.event(MouseDraggedEvent.class, e));
}
@Override
public void mouseMoved(MouseEvent e)
{
Events.trigger( emitter, SwingEvents.event(MouseEnteredEvent.class, e));
}
所以我可以通过
处理每个事件Events.on(component, new Function<MouseEnteredEvent, Void>()
{
public Void apply(MouseEnteredEvent e)
{
System.out.println("Mouse Entered");
return null;
}
});
BTW,Events.on,Events.trigger
是我的函数函数。
答案 0 :(得分:1)
据我所知,你想要做的是控制对象的实例化。因此,我会检查factory method和abstract factory的相应创作模式。
如果您认为某个映射器适合您,您可以查看Dozer项目。
希望我帮忙!