这是一个在Swing面板中执行的actionPerformed,其中包含来自框架的自定义按钮,这些按钮会对其类进行加扰,因此所有方法都是a():String或b():void,并且无法确定它实际上是什么。
我得到了编译器错误,因为当我继承这个按钮类时,编译器会找到一个():void a():Java中不允许的字符串。我的解决方案是使用这样的适配器模式:
public abstract class FactoryButton {
private CustomButton button;
public FactoryButton(int width, int height) {
button = new DynButton();
button.setSize(width, height);
}
public DynButton getButton() {
return button;
}
}
所以我的FactoryButton将CustomButton类作为私有成员。 FactoryButton是另一个名为FactorySelectionButton的Button类的父级,它执行的操作我以前能够获取事件的来源:
@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() instanceof FactorySelectionButton) {
// User selected a factory
selectedItem = ((FactorySelectionButton) arg0.getSource()).getFactory();
// Close the screen, so control returns back to the parent window
cancel();
} else {
// other buttons implementation
}
}
但是现在因为我解决了适配器模式的一个问题,我有另外一个arg0.getSource()不再给我FactorySelectionButton但它现在给了一个CustomButton,这让我无法知道按下哪个自定义按钮。
不丢弃自定义按钮的原因是我必须使用框架,我必须使用它并且工厂数量可以增长所以我不想要硬编码按钮。
所以任何人都知道如何解决这个问题?
我通过循环遍历所有组件并检查它们是否有我需要的按钮找到了解决方法,并仔细检查它是否真的是我想要的类的实例。
@Override
public void actionPerformed(ActionEvent arg0) {
for (FactoryButton component : components) {
if(component.getButton().equals(arg0.getSource()) && component instanceof FactorySelectionButton)
selectedItem = ((FactorySelectionButton) component).getFactory();
return;
}
//other buttons implementation
}