80 likes | 361 Views
Introduction to Java Programming Lecture 4 Using JOptionPane. Spring 2008. Displaying Text in a Dialog Box ( 使用 JOptionPane 來顯示 ). Display ( 顯示 ) 顯示資料的方式 : Command Windows, Graphic Window, Dialog Box … Class JOptionPane 提供了 Dialog Box 的顯示方式 Packages 一組已經寫好了的 classes
E N D
Introduction to Java ProgrammingLecture 4Using JOptionPane Spring 2008
Displaying Text in a Dialog Box(使用 JOptionPane 來顯示) • Display (顯示) • 顯示資料的方式 : Command Windows, Graphic Window, Dialog Box … • Class JOptionPane提供了 Dialog Box 的顯示方式 • Packages • 一組已經寫好了的 classes • 相類似的 classes 組成 packages • 所有的 packages 被稱為 Java class library 或 Java applications programming interface (Java API) • JOptionPane是 javax.swing這個 package 裡的一個 class, 同時也包含其他 Graphical User Interfaces (GUIs) 的 classes
Displaying Text in a Dialog Box //檔名 : Welcome.java //利用 java package javax.swing 顯示數行文字 import javax.swing.JOptionPane; // program uses JOptionPane public class Welcome { // main method begins execution of Java application public static void main( String args[] ) { JOptionPane.showMessageDialog( null, "Welcome\nto\nJava\nProgramming!" ); System.exit( 0 ); // terminate application with window } // end method main } // end class Welcome
Inputing using JOptionPane(使用 JOptionPane 來輸入資料) //檔名 : Addition.java //整數相加 Addition program that displays the sum of two numbers. // Java packages import javax.swing.JOptionPane; // program uses JOptionPane public class Addition { // main method begins execution of Java application public static void main( String args[] ) { String firstNumber; // first string entered by user String secondNumber; // second string entered by user
int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 // read in first number from user as a String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a String secondNumber= JOptionPane.showInputDialog("Enter second integer" ); number1 = Integer.parseInt( firstNumber ); // convert numbers from number2 = Integer.parseInt( secondNumber );// type String to type int sum = number1 + number2; // add numbers JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE ); System.exit( 0 ); // terminate application with window } // end method main } // end class Addition