Search code examples
javaadapterjava-6

Adapter pattern with Buttons, adaptor class has to know which button was pressed


This is an actionPerformed in a Swing panel with custom buttons from a framework which scrambles their classes so all methods are a():String or b():void and there is no way to make out what it actually is.

I got a compiler error becaus when I inherit this button class the compiler find a():void an a():String which is not allowed in Java. My solution was to use the adapter pattern like this:

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

So my FactoryButton has the CustomButton class as a private member. The FactoryButton is the parent of another Button class named FactorySelectionButton which has an action performed where I used to be able to get the source of the event:

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

But now since I solved one problem with the adapter pattern I have another the arg0.getSource() no longer gives me the FactorySelectionButton but it now gives a CustomButton which gives me no way to know which custom button is pressed.

The reason for not throwing away the custom button is that I am bound to the framework, I have to use it and the amount of factories can grow so I don't want hardcoded buttons.

So anyone have an idea on how I can fix this?


Solution

  • I found a way around it by looping over all my components and checking whether they have the button I need and they double checking whether it's really an instance of the class I want.

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