// File: GUI_Example.java // Demonstrates methods showInputDialog, and showMessageDialog of the // JOPtionPane class. These methods enable input and output of // strings, using simple Graphical User Interfaces (GUI's). // // Also shows how to create a scrollable window for output: // 1. Create a JTextArea object with a specified number of rows // and columns // 2. Use method setText to assign a string to the JTextArea obj // 3. To get scroll bars around the JTextArea obj, create a // JScrollPane obj with the JTextArea obj as a parameter. // 4. Display window and contents using showMessageDialog method // NOTE: As shown below, this is "easier DONE than SAID!" :-) import javax.swing.* ; // for classes JOPtionPane & JTextArea public class GUI_Example { // Basic input and output public static void main(String[] args) { // show input box and assign value entered to String obj "input" String input = JOptionPane.showInputDialog("Enter a number") ; int aNumber = Integer.parseInt(input); // make it an int // display the input number in an output box JOptionPane.showMessageDialog(null, "The input is " + aNumber) ; // overloaded showInputDialog method - the 3rd parameter displays // in the title bar and the fourth displays "?" icon input = JOptionPane.showInputDialog(null,"Enter a number", "\u00BFQue numero?", JOptionPane.QUESTION_MESSAGE) ; aNumber = Integer.parseInt(input) ; // fourth parameter means "no icon" JOptionPane.showMessageDialog(null, "The input is " + aNumber, "Back atcha!", JOptionPane.PLAIN_MESSAGE) ; // A JTextArea is a rectangular output area of rows and columns int rows = 25 ; int columns = 40 ; JTextArea outArea = new JTextArea(rows,columns) ; // create humongous, multi-line o/p string String output = "" ; for(int i = 0 ; i < 100 ; i++ ) { String blanks = " " ; for( int j = 0 ; j < i ; j++) { blanks += " " ; } output += blanks + i + "\n" ; } // Assign the output string to the output area outArea.setText(output) ; // The JScrollPane puts scroll bars around the output area JOptionPane.showMessageDialog(null,new JScrollPane(outArea)) ; // The same area using a title and no icon JOptionPane.showMessageDialog(null,new JScrollPane(outArea), "Output Area", JOptionPane.PLAIN_MESSAGE); // next statement required when GUI's are used System.exit(0) ; } }