Java Swing 101 Basic Input and Output using

Java Swing 101 Basic Input and Output using Java Swing.

Learning Objectives • Be able to use Java’s Swing class to make windows applications • Be able to convert from String to int and double.

GUI 101 with javax. swing // Fig. 3. 17: Dialog 1. java // Printing multiple lines in dialog box. import javax. swing. JOption. Pane; Look at java docs help files for JOption. Pane to find out additional methods. public class Dialog 1 { public static void main( String args[] ) { // display a dialog with the message JOption. Pane. show. Message. Dialog( null, "Welcomenton. Java" ); } // end main } // end class Dialog 1

// Fig. 3. 18: Name. Dialog. java // Basic input with a dialog box. import javax. swing. JOption. Pane; Input with swing public class Name. Dialog { public static void main( String args[] ) { // prompt user to enter name String name = JOption. Pane. show. Input. Dialog( "What is your name? " ); // create the message String message = String. format( "Welcome, %s, to Java Programming!", name ); // display the message to welcome the user by name JOption. Pane. show. Message. Dialog( null, message ); } // end main } // end class Name. Dialog

Swing input stuff • It only enters a String, not a double or int. • So to enter numbers you will need to convert them to integers or doubles • To convert a String into an integer. • int answer=Integer. parse. Int(name); • To convert to a double: • double answer=Double. parse. Double(name);

import javax. swing. JOption. Pane; public class Name. Dialog { public static void main( String [] args) { // prompt user to enter name String name = JOption. Pane. show. Input. Dialog( "What is your name? " ); //Prompt for the age String age. String =JOption. Pane. show. Input. Dialog( "What is your age? " ); int age = Integer. parse. Int(age. String); Convert input to integer // create the message String message = String. format( "Welcome, %s, to Java Programming! n %d", name, age ); // display the message to welcome the user by name JOption. Pane. show. Message. Dialog( null, message ); } // end main %d for } // end class Name. Dialog int, Use %f for double

Dice Game Challenge • Convert the dice game to a Windows application using Swing.
- Slides: 7