Search code examples
javaswingdialogawtwindowlistener

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


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=new 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?


Solution

  • 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:

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