3

在 Swing Gui 中,每个组件都根据设计引用其自己的数据模型来显示数据。尽管它们不引用通用模型,但由于程序的语义,有时组件可以相互“依赖”。

例如:如果 Gui 有一个显示/隐藏表格的 JToggleButton 和另一个 JButton,其 actionListener 计算该表格中的行数,则在未选择前者时必须禁用后者(并且表格不可见)。事实上——让我们假设——计算不可见表的行数可能会导致不一致的状态。例如,当表格被隐藏时,JButton 的 actionListener 调用设置为 null 的变量的方法。

我知道这是一个非常微不足道的例子。但是我经常遇到这种情况,我不得不查看组件之间的所有这些依赖关系。而且我不得不禁用一些组件,以防止用户在错误的时间单击错误的按钮,从而使程序进入不一致的状态。

因此,我开始想知道是否有一种更有条理和标准的方法来解决这个问题,而不仅仅是浏览代码并在这里和那里放置一些 setEnable(false),我注意到存在依赖关系。

我认为,一种可行的方法可能是拥有一个布尔值的依赖矩阵:接口的每个可能状态为一行,接口的每个组件为一列。如果在状态i ,必须禁用组件j ,则matrix[i][j]真。否则为假。

你怎么看?有什么设计模式可以解决这个问题吗?

干杯

4

1 回答 1

0

我不完全确定您的“状态 i”是什么意思,这是多么普遍或具体。在某些情况下,您可以使用如下所示的简单辅助对象,并为每个观察到的状态提供一个实例。您所依赖的组件的状态不会在编译时依赖于相关组件,但会引用其 DependentComponents 的实例。

import java.awt.Component;
import java.util.HashSet;
import java.util.Set;

/**
 * Handles components which are enabled/disabled based on some condition
 */
public class DependentComponents {
    /**
     * Internal set of components handled by this object
     */
    final private Set<Component> components = new HashSet<>();

    /**
     * Each dependent component should be added to the set by this method
     * 
     * @param component A component which is to be added
     */
    public void register(final Component component) {
        this.components.add(component);
    }

    /**
     * Enables or disables all the components, depending on the value of the parameter b. 
     * 
     * @param b If <code>true</code>, all the components are enabled; otherwise they are disabled
     */
    public void setEnabled(boolean b) {
        for (Component component : this.components) {
            component.setEnabled(b);
        }
    }
}
于 2013-10-16T15:38:47.067 回答