Thursday, July 14, 2011

Can't Control Applet Close Window?

I spent way too many hours trying to find the answer to this question, so in the event that someone else runs into the same problem, a search for WindowListener or JApplet or Applet will probably bring them here.

I am writing a popup applet to replace the Javascript prompt function--but with more caller control over the size of the text that the user can enter.  (It uses the JTextArea component.)  The way it works makes it easy to replace existing calls to prompt--instead, it has methods like this:


/**
* Replaces the Javascript prompt function.  It displays text in a text box, OK and Cancel buttons
* and returns a String if the user hits OK.
* @param msg: the prompt to the user
* @return: String
* @throws InterruptedException
* @throws BadLocationException
*/
 public String editableTextBox(String prompt, String defaultText, int rows, int columns);



/**
* Replaces the Javascript prompt function.  It puts up an empty text box, OK and Cancel buttons,
* and returns a String if the user hits OK.
* @param msg: the prompt to the user
* @return: String
* @throws InterruptedException
* @throws BadLocationException
*/
 public String inputTextBox(String prompt, int rows, int columns);


A little weird, but the way that this works is that it pops up a window containing these components, and then goes into a sleep loop until the user hits the OK or Cancel button.  This worked just fine, but the problem was what to do if a user hits the close window box on the popup, instead of hitting the Cancel button?

I thought that I could turn on the WindowListener interface, and catch the window closing or window close events, and from there, set the flags that simulated the user hitting Cancel--but that did not work.

 So I put the same code in the stop and destroy methods of the applet--but there was no way to force that looping thread to get control and see that we were simulating Cancel.  So I took what might seem like the least beautiful approach.  In the popup window (which is a JFrame):

     setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

The user can hit the close button all day, and nothing will happen.  He has to hit OK or Cancel.

No comments: