Page 256 - PowerPoint Presentation
P. 256
CAVITE STATE UNIVERSITY
TRECE MARTIRES CITY CAMPUS
Department of Information Technology DCIT 111 - Advanced Programming
JOptionPane
A Dialog window is an independent subwindow meant to carry temporary notice
apart from the main Swing Application Window. Most Dialogs present an error message or
warning to a user, but Dialogs can present images, directory trees, or just about anything
compatible with the main Swing Application that manages them. For convenience, several
Swing component classes can directly instantiate and display dialogs. To create simple,
standard dialogs, you use the JOptionPane class.
The code for simple dialogs can be minimal. For example, here is an informational dialog:
import javax.swing.JOptionPane;
public class JOptionExample {
public static void main(String args[]) {
JOptionPane.showMessageDialog(null, "Here's an example of a Message Dialog",
“Sample Dialog Box”, JOptionPane.PLAIN_MESSAGE);
}
}
JOptionPane.showMessageDialog allows us to display simple dialog boxes. The first
parameter “null” displays the dialog box in the middle of the screen, the second parameter
defines the text that we want to be displayed inside the box, the third parameter defines the
text that we want to be displayed as header, and the fourth parameter allows us to choose a
particular icon. Every parameter is separated by a comma (,).
Using JOptionPane to get input
import javax.swing.JOptionPane;
public class JOption {
public static void main(String[] args) {
String n = JOptionPane.showInputDialog("Enter your name!");
// in C++ this looks like the combination of cout << and cin >>
JOptionPane.showMessageDialog(null, "Hello " + n,
"Sample Output", JOptionPane.INFORMATION_MESSAGE);
// and this is like cout << + calling the variable name
}
}
JOptionPane.QUESTION_MESSAGE Icons used by JOptionPane
JOptionPane.INFORMATION_MESSAGE
JOptionPane.WARNING_MESSAGE
JOptionPane.ERROR_MESSAGE question information warning error
JOptionPane's icon support lets you easily specify which icon the dialog displays. You
can use a custom icon, no icon at all, or any one of four standard JOptionPane icons (question,
32