3

In a Swing Gui, every component refers, by design, to its own data model to display data. Although they don't refer to a common model, sometimes components can be "dependent" to each other, because of the semantic of the program.

For example: if the Gui has a JToggleButton that shows/hides a table and another JButton, whose actionListener counts the rows in that table, the latter must be disabled when the former is not selected (and the table not visible). Indeed - let's suppose- counting the rows of a non visible table might lead to an inconsistent state. Say, for example, that when the table is hidden the JButton's actionListener calls a method on a variable that is set to null.

I know this is a very trivial example. But it has happened to me, quite often, that I had to kind of look at all these dependencies between components. And I had to disable some components, so as to prevent the user from bringing the program to an inconsistent state, by clicking on the wrong button at the wrong time.

Therefore, I have started wondering if there is a more organized and standard way to address this problem, than just skimming trough the code and place some setEnable(false), here and there, where I notice there is a dependency.

A way to go, I think, could be to have a dependency matrix of boolean values: one row for each possible state of the interface, and one column for each component of the interface. matrix[i][j] would be true if at state i, the component j must be disabled. and false otherwise.

What to you think about it ? Is there any kind of design pattern to address this problem ?

cheers

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 に答える