带按钮的适配器模式,适配器类必须知道按下了哪个按钮

时间:2018-03-05 15:50:18

标签: java adapter java-6

这是一个在Swing面板中执行的actionPerformed,其中包含来自框架的自定义按钮,这些按钮会对其类进行加扰,因此所有方法都是a():String或b():void并且无法确定它实际是什么。< / p>

我得到了编译器错误,因为当我继承这个按钮类时,编译器会找到一个():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,它让我无法知道按下哪个自定义按钮。

不丢弃自定义按钮的原因是我必须使用框架,我必须使用它,工厂数量可以增长,所以我不想要硬编码按钮。

所以任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我通过循环遍历所有组件并检查他们是否有我需要的按钮找到了解决方法,并仔细检查它是否真的是我想要的类的实例。

@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
}