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=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:
ActionListener
- for theJButton
instance.WindowListener
- for theDialog
instance. More specifically, you'll need to listen for thewindowClosing()
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;
}
}
精彩评论