Next page | Contents page |

JOptionPane - common dialogues

Exercise 23's Window is useless, even compared to Squarer (in Exercise 1) - it doesn't even take a number in and square it. We can do that by using some standard dialogue boxes for text input and message display. Class javax.swing.JOptionPane has many standard dialogues, eg

There are several constants of the form JOptionPane.xxx_OPTION where xxx can be CANCEL, OK, OK_CANCEL, YES_NO, etc

Those calls need parameters of course. Some examples follow.

Message dialogue

	JOptionPane.showMessageDialog (w, "message");

w is the parent window, in the sense of the windowing system (not superclass).

Confirmation dialogue

	int response = JOptionPane.showConfirmDialog (w, 
		new String [] { "line 1", "line 2"},
		"title", JOptionPane.YES_NO_OPTION,
		JOptionPane.WARNING_MESSAGE); // icon kind
	switch (response)
	{
	case JOptionPane.YES_OPTION: yesAction (); break;
	case JOptionPane.NO_OPTION:  noAction ();  break;
	case JOptionPane.CLOSED_OPTION:; // leave unchanged
	}

Input dialogues

	String response = JOptionPane.showInputDialog (w, "Enter x:");

	String response = (String) JOptionPane.showInputDialog (
		w, // Parent window
		"Destination?",					 // Prompt
		"Select destination",			 // Title
		JOptionPane.QUESTION_MESSAGE,	 // Icon kind
		null,							 // No icon file
		new String []					 // Choices
			{ "Heathrow", "Gatwick", "Stansted" },
		"Heathrow");					// Default choice

NB: There are many different overloaded versions of the common dialogue methods - see the API documentation.

Next page | Contents page |