开发者

Java beginner: pattern to track object properties changes in dialog box (save prompt on dialog close)

开发者 https://www.devze.com 2023-04-01 02:00 出处:网络
There is some entity: public class Entity { private String name; public String getName() { return name; } public void setName(String name)

There is some entity:

public class Entity
{
  private String name;

  public String getName()
  {
    return name;
  }

  public void setName(String name)
  {
    this.name=name;
  }

  // many other properties ...
}

In the program user change entity in dialog:

Entity entity=ne开发者_如何学JAVAw Entity();

boolean modal=true;
Dialog dlg=new Dialog(modal);
dlg.setEntity(entity);
dlg.setVisible(true);

then user change some properties and click close button. Program should prompt user about saving changes.

I'm trying to avoid reinventing the wheel, so is there in Java some ready practice to realize this schema?


First, you'll need to register two event listeners:

  1. ActionListener - for the JButton instance.
  2. WindowListener - for the Dialog instance. More specifically, you'll need to listen for the windowClosing() event.

To show a "save" dialog in the event of this dialog closing, you can use a standard JOptionPane instance. More specifically, you can show an option dialog (i.e. JOptionPane.showOptionDialog(...). And based on the return value, persist the changes made to the Entity object by the user.

See also:

  • How to Make Dialogs

Also, I highly recommend that you use Swing components, not AWT components.


If you want a model to notify a view or a controller of changes, then using PropertyChangeListener is a common practice.

However, in a situation so simple, you can live with simply a dirty flag implemented in the view (the dialog itself).


You could utilise the Command pattern. This is typically used for undo-redo, but it can also be used to track actions that a user has performed.


If you don't care about undo, you can use a boolean to track changes. For example:


public class Entity
{
  private boolean changed;
  private String name;

  public Entity()
  {
    changed = false;
    name = StringUtils.EMPTY; // no pesky nulls.
  }

  ...

  public boolean isChanged()
  {
    return changed;
  }

  public void setName(final String newValue)
  {
    name = StringUtils.defaultString(newValue); // Again with the pesky nulls.
    changed = true;
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号