package hirondelle.stocks.util.ui;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import hirondelle.stocks.util.Args;
public abstract class StandardEditor {
protected StandardEditor (String aTitle, JFrame aParent, CloseAction aCloseAction) {
Args.checkForContent(aTitle);
Args.checkForNull(aParent);
fTitle = aTitle;
fParent = aParent;
fCloseAction = aCloseAction.getValue();
}
protected enum CloseAction {
DISPOSE(JDialog.DISPOSE_ON_CLOSE),
HIDE(JDialog.HIDE_ON_CLOSE);
int getValue(){
return fAction;
}
private final int fAction;
private CloseAction(int aAction){
fAction = aAction;
}
}
public final void showDialog(){
boolean isModal = true;
fDialog = new JDialog(fParent, UiUtil.getDialogTitle(fTitle), isModal);
fDialog.setDefaultCloseOperation(fCloseAction);
fDialog.setResizable(false);
addCancelByEscapeKey();
JPanel standardLayout = new JPanel();
standardLayout.setLayout(new BoxLayout(standardLayout, BoxLayout.Y_AXIS));
standardLayout.setBorder(UiUtil.getStandardBorder());
standardLayout.add(getEditorUI());
standardLayout.add(getCommandRow());
fDialog.getContentPane().add(standardLayout);
UiUtil.centerOnParentAndShow(fDialog);
}
public final void dispose(){
fDialog.dispose();
}
protected abstract JComponent getEditorUI();
protected abstract void okAction();
private final String fTitle;
private final JFrame fParent;
private JDialog fDialog;
private final int fCloseAction;
private JComponent getCommandRow() {
JButton ok = new JButton("OK");
ok.addActionListener( new ActionListener() {
@Override public void actionPerformed(ActionEvent event) {
okAction();
}
});
fDialog.getRootPane().setDefaultButton( ok );
JButton cancel = new JButton("Cancel");
cancel.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent event) {
closeDialog();
}
});
List<JComponent> buttons = new ArrayList<>();
buttons.add(ok);
buttons.add(cancel);
return UiUtil.getCommandRow(buttons);
}
private void addCancelByEscapeKey(){
String CANCEL_ACTION_KEY = "CANCEL_ACTION_KEY";
int noModifiers = 0;
KeyStroke escapeKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, noModifiers, false);
InputMap inputMap =
fDialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
;
inputMap.put(escapeKey, CANCEL_ACTION_KEY);
AbstractAction cancelAction = new AbstractAction(){
@Override public void actionPerformed(ActionEvent e){
closeDialog();
}
};
fDialog.getRootPane().getActionMap().put(CANCEL_ACTION_KEY, cancelAction);
}
private void closeDialog(){
fDialog.dispose();
}
}