I want to implement a Swing Input Dialog with different options shown in a combo box. My specific case is for Contact creation, the end user can choose between existing Contacts or create a new one himself.
So I've got this static method which basically returns a new instance of a JOptionPane
, which has the available selection objects out of the box. Note this code creates, let's say the parent dialog, which offers selecting an existing contact or clicking on the button to create a new one:
/**
*
* @param message
* Here I've got a JPanel which allows the end user to show-hide
* the Contact creation dialog
* @param contacts
* Contact possibilities
* @return reference to the created JOptionPane
*/
public static JOptionPane newContactOptionPane(Object message,
Set<XmlContact> contacts) {
Object[] contactPossibilities = new Object[contacts.size()];
int index = 0;
for (XmlContact contct : contacts) {
contactPossibilities[index] = String.format("%s %s, %s",
contct.get_Surname1(), contct.get_Surname2(),
contct.get_Name());
index++;
}
JOptionPane optPane = new JOptionPane();
JOptionPane.showInputDialog(optPane, message, "Seleccionar Contacto",
JOptionPane.QUESTION_MESSAGE, null, contactPossibilities,
contactPossibilities[0]);
return optPane;
}
The invoker code would be something like:
JOptionPane contactSelectionPane =
ViewUtils.newContactOptionPane(createContactPanel, xmlContacts);
XmlContact selectedContact =
(XmlContact) contactSelectionPane.getValue();
Later on, I would like to recover the selected value using JOptionPane#getValue()
method.
The desired behaviour is to show the form for Contact creation when clicking Crear nuevo contacto, so the previous JDialog will be hidden:
I've got two reasons for keeping the reference at the invoker code, the first one is because I would like to wrap the option pane to make it return an XmlContact
object instead of an String and having to search it again the possible options once and again in my invoker code. The other one is because I want to keep a reference of contactSelectionPane
for enabling a button into createContactPanel
to show/hide it.
Now the contactSelectionPane.getValue()
is obviously returning an String
, which forces me to check the options again. How can I implement that?