The best approach to dual state action

I recently implemented Actionthat switches the activated status of a business function. Whenever a user invokes an action, I set a boolean flag: "willEnable" to determine whether the next call will enable or disable the function. Similarly, I am updating the action title, short description, and icon to reflect the new state. Then in my method, actionPerformed(...)I perform another state based action willEnable.

  • Is this the right approach or can someone recommend a better one (as I suspect this is a common problem)? (I see that it JToggleButtonacts like a button with two states, but I want this action to be JMenuBar, as well JButton, so don't think that it is necessary).

EDIT

In particular, how do they deal with applications such as IDEA? Will they use actions with several states (as indicated above) or exchange anotherAction with the specified one JButtonusing setAction(Action)? Perhaps this approach is better?

  1. When updating action properties, can I rely on GUI components to be initialized in that Action(for example JButton), automatically repainting themselves? What if JButton size changes result? Do I need to repeat the content check JPanelmyself?
  2. Does the name of the action change the bad thing to do? This is the only way I can change the text of JButton, but I understand that the name must remain constant if the action is placed in ActionMap.

Thanks in advance.

+3
source share
2 answers

, GUI, "" ( Action ), . , erm, PropertyChangeEvent: , .

, , . , . ToggleEnabledStatus, , . , , Action, willEnable, , erm, .

, ToggleButtonModel Action . , ,

+2

.

, ( ) . , , , . ,

interface IState {
  void doAction();
  boolean isEnabled();
}

class EnabledState implement IState {
  void doAction() {
    setState(new DisabledState());
    // do something
  }
  boolean isEnabled() {return true;}
}

class DisabledState implement IState {
  void doAction() {
    setState(new EnabledState());
    // do nothing
  }
  boolean isEnabled() {return false;}
}

private IState state = new DisabledState(); // default is disabled
private PropertyChangeSupport support = new PropertyChangeSupport(this);

void setState(IState state) {
  if (this.state != state) {
    IState oldState = this.state;
    this.state = state;
    support.firePropertyChange("enabled", oldState.isEnabled(), state.isEnabled());
  }
}

void doAction() {
  state.doAction();
}

, , , , , .

+3

Source: https://habr.com/ru/post/1721781/


All Articles