I want to wrap the UI components in my Java Application to keep my production code independent from a concrete UI library. I have a problem now, if I want to add components on another because the concrete UI element is not known by the wrapper classes.

How can I handle the ordering of elements without revealing the underlaying UI library?

public abstract class UIComponent {

}

public class UIPanel extends UIComponent {
    private JPanel jpanel;

    public UIPanel() {
        this.jpanel = new JPanel();
    }

    public void addUIComponent(UIComponent component) {
        // how can I add the concrete jbutton from a UIButton
        // to the concrete jpanel of this UIPanel?  
    }
}

public class UIButton extends UIComponent {
    private JButton jbutton;

    public UIButton() {
        this.jbutton = new JButton();
    }
}
有帮助吗?

解决方案

Define a method in the UIComponent

public JComponent getRealComponent();

Then UIPanel and UIButton overriding the method and return JPanel and JButton accordingly.

The method should be like this

public void addUIComponent(UIComponent component) {
  getRealComponent().add(component.getRealComponent());
}

其他提示

I did something similar for an MVP architecture that we use. The rule was to have no application logic in the UI, and no reference to Swing components in the Presenters. We accomplished that by:

  • Creating an Interface that the Swing GUI implemented. The presenters had a handle to this Interface and is how it interacted with the UI.

  • Using enums (or String constants, or whatever) that acted as a key for each field. The UI would register each component with the specified key, and the Presenter would then act upon the UI using these field keys.

Code in the Presenter would look something like this:

ui.setEditable(AddressBook.NAME, false);
ui.setValue(AddressBook.NAME, "John Doe");

The UI would receive these events and make the JTextField for the NAME field read-only, populated with the given text.

So based on your question, you want to add JButtons dynamically to the UI? We wouldn't normally do that. In our scenerio, the Swing implementor of the UI interface would already have all of it's components created and registered.

However, if that's what's really needed, I imagine I'd need a method that looked like this on the UI (based on an Address Book example):

ui.addCommandButton(AddressBook.SOME_COMMAND, "Button Text");

Or, if you didn't have the key and wanted the UI to generate a new field dynamically, maybe something like:

Object key = ui.addCommandButton("Button Text");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top