0

For a Java college task, I have to create a dialog box that contains a form field using the MVC observer pattern.

I see from this post that I'm unable to attach an event listener to the ok button.

Add actionlistener to a button in joptionPane (java)

I'm only just starting to learn Java for the purpose of this course but from what I understand, the listener should be in the controller which should then update the model.

I'm therefore confused about how to pass the value of form field to the controller if I'm only able to access the data from the result of the button click like so:

int option = optionPane.showOptionDialog(frame, spinner, "Create a new alarm", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);                

if (option == JOptionPane.OK_OPTION) {
   ...

Should I just update the model directly from the view or am I missing something?

Alternatively, I tried creating a custom button inside the dialog but I was unable to close the dialog after the button was clicked because the dialog was outside the scope of the listener.

We're not using Spring.

Asa Carter
  • 2,207
  • 5
  • 32
  • 62
  • And the listener to the `spinner` – MadProgrammer Apr 13 '18 at 21:24
  • Ah that’s a good idea. I should have stated though I needed the listener on the button to add the value of the spinner to an array. – Asa Carter Apr 13 '18 at 23:38
  • Well, your question is a little contraindicative. If you say you can't use a custom button because you need to close the dialog, but you want the button to add the item to the array - so from that, I can only deduce that you want to close the dialog and add the item to the array, so simply taking the value from the `spinner` when the dialog is closed (in the normal operation) seems like the likely cause of action – MadProgrammer Apr 13 '18 at 23:42
  • Have said that, you could do something like [Disable ok button on JOptionPane.dialog until user gives an input](https://stackoverflow.com/questions/14334931/disable-ok-button-on-joptionpane-dialog-until-user-gives-an-input/14335083#14335083) and [ActionListener on JOptionPane](https://stackoverflow.com/questions/12828389/actionlistener-on-joptionpane/12829264#12829264) or [JOptionPane Passing Custom Buttons](https://stackoverflow.com/questions/14591089/joptionpane-passing-custom-buttons/14591165#14591165) – MadProgrammer Apr 13 '18 at 23:44
  • or even [Closing a runnable JOptionPane](https://stackoverflow.com/questions/22979504/closing-a-runnable-joptionpane/22979571#22979571) – MadProgrammer Apr 13 '18 at 23:44
  • That’s how it’s working at the moment. I’ve instantiated the array in the model. But I add the spinner value to the array in the model directly from the view. Is that something I can do? – Asa Carter Apr 13 '18 at 23:46
  • Sure, make a custom `JDialog` and take full control - or look at any of the other examples I've linked – MadProgrammer Apr 14 '18 at 00:23

0 Answers0