gpt4 book ai didi

java - 解耦 CardLayout 面板

转载 作者:行者123 更新时间:2023-11-30 09:00:31 24 4
gpt4 key购买 nike

想了解您对解耦 CardLayout 面板的最佳方式的意见。现在我正在使用一个支架面板,它看起来像:

class CardHolder extends JPanel implements ActionListener {

然后子面板是:

class SubPanel extends JPanel {
private List<ActionListener> listeners;
private void fireActionListeners(ActionEvent e) {
for (ActionListener listener : listeners) {
listener.actionPerformed(e);
}
}

当我将 SubPanel 添加到 CardHolder 时,我将其添加为 ActionListener。然后,当在 SubPanel 上按下按钮时,我通过将事件发送到所有附加的监听器(即 CardHolder)来传播操作事件。

这种方法可以接受吗?还是我遗漏了什么?

我查看了使用观察者模式,但它在这里似乎不正确,因为 SubPanel 不会改变状态,只按下了一个按钮,它期望发生一些事情。

最佳答案

It is a wizard of sorts, but the path they take through the wizard will change depending on options they choose, in this case there is a change in the screen depending on whether the user is importing or exporting data with the wizard.

好吧,在这种情况下,我认为一种类似于 this article 中描述的方法与将 ActionListeners 添加到您的持卡人相比,这是一个更好的设计选择。

关键是要有一个向导模型来保存向导过程中必须填写的相关数据。这个模型必须有一个机制来通知它的数据何时发生变化,以便让持卡人知道发生了什么事情并且它需要做出相应的 react (即:改变卡片流程,根据需要更换卡片,更新卡片等).当然,您的卡片应该有权通过 getter/setter 修改模型,因为它们会修改模型,而不是卡片持有者。

从模型中实现通知链的最简单方法是使用 PropertyChangeSupport如下所示。一种更灵活的机制是创建您自己的 ModelEventModelListener,但是否值得走那么远取决于您。

例子

这是一个非常简单的模型。卡片应更新此模型,持卡人应订阅 PropertyChangeListener 以监听属性更改(即:“type”属性)。

public enum Type {
IMPORT, EXPORT
}

public class WizardModel {

private PropertyChangeSupport propertyChangeSupport;
private Type type;

public WizardModel() {
super();
this.type = Type.IMPORT;
this.propertyChangeSupport = new PropertyChangeSupport(this);
}

public Type getType() {
return type;
}

public void setType(Type newType) {
Type oldType = this.type;
this.type = newType;
firePropertyChangeEvent(new PropertyChangeEvent(this, "type", oldType, newType));
}

public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}

public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(propertyName, listener);
}

protected void firePropertyChangeEvent(PropertyChangeEvent evt) {
for (PropertyChangeListener l : propertyChangeSupport.getPropertyChangeListeners(evt.getPropertyName())) {
l.propertyChange(evt);
}
}
}

关于java - 解耦 CardLayout 面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26756805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com