JAVA: An Introduction to
Problem Solving & Programming, 8th Ed.
By Walter Savitch.
ISBN 01334462033 © 2018 Pearson Education, Inc., Hoboken, NJ.
All Rights Reserved
Listing 7.1 |
/** Reads 7 temperatures from the user and shows which are above and which are below the average of the 7 temperatures. */ import java.util.Scanner; public class ArrayOfTemperatures { public static void main (String [] args) { double [] temperature = new double [7]; // Read temperatures and compute their average: Scanner keyboard = new Scanner (System.in); System.out.println ("Enter 7 temperatures:"); double sum = 0; for (int index = 0 ; index < 7 ; index++) { temperature [index] = keyboard.nextDouble (); sum = sum + temperature [index]; } double average = sum / 7; System.out.println ("The average temperature is " + average); // Display each temperature and its relation to the average: System.out.println ("The temperatures are"); for (int index = 0 ; index < 7 ; index++) { if (temperature [index] < average) System.out.println (temperature [index] + " below average."); else if (temperature [index] > average) System.out.println (temperature [index] + " above average."); else //temperature[index] == average System.out.println (temperature [index] + " the average."); } System.out.println ("Have a nice week."); } } |
Listing 7.2 |
/** Reads temperatures from the user and shows which are above and which are below the average of all the temperatures. */ import java.util.Scanner; public class ArrayOfTemperatures2 { public static void main (String [] args) { Scanner keyboard = new Scanner (System.in); System.out.println ("How many temperatures do you have?"); int size = keyboard.nextInt (); double [] temperature = new double [size]; // Read temperatures and compute their average: System.out.println ("Enter " + temperature.length + " temperatures:"); double sum = 0; for (int index = 0 ; index < temperature.length ; index++) { temperature [index] = keyboard.nextDouble (); sum = sum + temperature [index]; } double average = sum / temperature.length; System.out.println ("The average temperature is " + average); // Display each temperature and its relation to the average: System.out.println ("The temperatures are"); for (int index = 0 ; index < temperature.length ; index++) { if (temperature [index] < average) System.out.println (temperature [index] + " below average."); else if (temperature [index] > average) System.out.println (temperature [index] + " above average."); else //temperature[index] == average System.out.println (temperature [index] + " the average."); } System.out.println ("Have a nice week."); } } |
Listing 7.3 |
import java.util.Scanner; /** Class for sales associate records. */ public class SalesAssociate { private String name; private double sales; public SalesAssociate () { name = "No record"; sales = 0; } public SalesAssociate (String initialName, double initialSales) { set (initialName, initialSales); } public void set (String newName, double newSales) { name = newName; sales = newSales; } public void readInput () { System.out.print ("Enter name of sales associate: "); Scanner keyboard = new Scanner (System.in); name = keyboard.nextLine (); System.out.print ("Enter associates sales: $"); sales = keyboard.nextDouble (); } public void writeOutput () { System.out.println ("Name: " + name); System.out.println ("Sales: $" + sales); } public String getName () { return name; } public double getSales () { return sales; } } |
Listing 7.4 |
import java.util.Scanner; /** Program to generate sales report. */ public class SalesReporter { private double highestSales; private double averageSales; private SalesAssociate [] team; //The array object is //created in getData. private int numberOfAssociates; //Same as team.length /** Reads the number of sales associates and data for each one. */ public void getData () { Scanner keyboard = new Scanner (System.in); System.out.println ("Enter number of sales associates:"); numberOfAssociates = keyboard.nextInt (); team = new SalesAssociate [numberOfAssociates + 1]; for (int i = 1 ; i <= numberOfAssociates ; i++) { team [i] = new SalesAssociate (); System.out.println ("Enter data for associate " + i); team [i].readInput (); System.out.println (); } } /** Computes the average and highest sales figures. Precondition: There is at least one salesAssociate. */ public void computeStats () { double nextSales = team [1].getSales (); highestSales = nextSales; double sum = nextSales; for (int i = 2 ; i <= numberOfAssociates ; i++) { nextSales = team [i].getSales (); sum = sum + nextSales; if (nextSales > highestSales) highestSales = nextSales; //highest sales so far. } averageSales = sum / numberOfAssociates; } /** Displays sales report on the screen. */ public void displayResults () { System.out.println ("Average sales per associate is $" + averageSales); System.out.println ("The highest sales figure is $" + highestSales); System.out.println (); System.out.println ("The following had the highest sales:"); for (int i = 1 ; i <= numberOfAssociates ; i++) { double nextSales = team [i].getSales (); if (nextSales == highestSales) { team [i].writeOutput (); System.out.println ("$" + (nextSales - averageSales) + " above the average."); System.out.println (); } } System.out.println ("The rest performed as follows:"); for (int i = 1 ; i <= numberOfAssociates ; i++) { double nextSales = team [i].getSales (); if (team [i].getSales () != highestSales) { team [i].writeOutput (); if (nextSales >= averageSales) System.out.println ("$" + (nextSales - averageSales) + " above the average."); else System.out.println ("$" + (averageSales - nextSales) + " below the average."); System.out.println (); } } } public static void main (String [] args) { SalesReporter clerk = new SalesReporter (); clerk.getData (); clerk.computeStats (); clerk.displayResults (); } } |
Listing 7.5 |
import java.util.Scanner; /** A demonstration of using indexed variables as arguments. */ public class ArgumentDemo { public static void main (String [] args) { Scanner keyboard = new Scanner (System.in); System.out.println ("Enter your score on exam 1:"); int firstScore = keyboard.nextInt (); int [] nextScore = new int [3]; for (int i = 0 ; i < nextScore.length ; i++) nextScore [i] = firstScore + 5 * i; for (int i = 0 ; i < nextScore.length ; i++) { double possibleAverage = getAverage (firstScore, nextScore [i]); System.out.println ("If your score on exam 2 is " + nextScore [i]); System.out.println ("your average will be " + possibleAverage); } } public static double getAverage (int n1, int n2) { return (n1 + n2) / 2.0; } } |
Listing 7.6 |
/** A demonstration program to test two arrays for equality. */ public class TestEquals { public static void main (String [] args) { int [] a = new int [3]; int [] b = new int [3]; setArray (a); setArray (b); if (b == a) System.out.println ("Equal by ==."); else System.out.println ("Not equal by ==."); if (equals (b, a)) System.out.println ("Equal by the equals method."); else System.out.println ("Not equal by the equals method."); } public static boolean equals (int [] a, int [] b) { boolean elementsMatch = true; //tentatively if (a.length != b.length) elementsMatch = false; else { int i = 0; while (elementsMatch && (i < a.length)) { if (a [i] != b [i]) elementsMatch = false; i++; } } return elementsMatch; } public static void setArray (int [] array) { for (int i = 0 ; i < array.length ; i++) array [i] = i; } } |
Listing 7.7 |
import java.util.Scanner; /** A demonstration of a method that returns an array. */ public class ReturnArrayDemo { public static void main (String [] args) { Scanner keyboard = new Scanner (System.in); System.out.println ("Enter your score on exam 1:"); int firstScore = keyboard.nextInt (); int [] nextScore = new int [3]; for (int i = 0 ; i < nextScore.length ; i++) nextScore [i] = firstScore + 5 * i; double [] averageScore = getArrayOfAverages (firstScore, nextScore); for (int i = 0 ; i < nextScore.length ; i++) { System.out.println ("If your score on exam 2 is " + nextScore [i]); System.out.println ("your average will be " + averageScore [i]); } } public static double [] getArrayOfAverages (int firstScore, int [] nextScore) { double [] temp = new double [nextScore.length]; for (int i = 0 ; i < temp.length ; i++) temp [i] = getAverage (firstScore, nextScore [i]); return temp; } public static double getAverage (int n1, int n2) { return (n1 + n2) / 2.0; } } |
Listing 7.8 |
import java.util.Scanner; public class ListDemo { public static final int MAX_SIZE = 3; //Assumed > 0 public static void main (String [] args) { OneWayNoRepeatsList toDoList = new OneWayNoRepeatsList (MAX_SIZE); System.out.println ( "Enter items for the list, when prompted."); boolean moreEntries = true; String next = null; Scanner keyboard = new Scanner (System.in); while (moreEntries && !toDoList.isFull ()) { System.out.println ("Enter an item:"); next = keyboard.nextLine (); toDoList.addItem (next); if (toDoList.isFull ()) { System.out.println ("List is now full."); } else { System.out.print ("More items for the list? "); String ans = keyboard.nextLine (); if (ans.trim ().equalsIgnoreCase ("no")) moreEntries = false; //User says no more } } System.out.println ("The list contains:"); int position = toDoList.START_POSITION; next = toDoList.getEntryAt (position); while (next != null) //null indicates end of list { System.out.println (next); position++; next = toDoList.getEntryAt (position); } } } |
Listing 7.9 |
/** An object of this class is a special kind of list of strings. You can write the list only from beginning to end. You can add only to the end of the list. You cannot change individual entries, but you can erase the entire list and start over. No entry may appear more than once on the list. You can use int variables as position markers into the list. Position markers are similar to array indices, but are numbered starting with 1. */ public class OneWayNoRepeatsList { public static int START_POSITION = 1; public static int DEFAULT_SIZE = 50; //entry.length is the total number of items you have room //for on the list (its capacity); countOfEntries is the number of //items currently on the list. private int countOfEntries; //can be less than entry.length. private String [] entry; /** Creates an empty list with a given capacity. */ public OneWayNoRepeatsList (int maximumNumberOfEntries) { entry = new String [maximumNumberOfEntries]; countOfEntries = 0; } /** Creates an empty list with a capacity of DEFAULT_SIZE. */ public OneWayNoRepeatsList () { entry = new String [DEFAULT_SIZE]; countOfEntries = 0; // or replace these two statements with this(DEFAULT_SIZE); } public boolean isFull () { return countOfEntries == entry.length; } public boolean isEmpty () { return countOfEntries == 0; } /** Precondition: List is not full. Postcondition: If item was not on the list, it has been added to the list. */ public void addItem (String item) { if (!isOnList (item)) { if (countOfEntries == entry.length) { System.out.println ("Adding to a full list!"); System.exit (0); } else { entry [countOfEntries] = item; countOfEntries++; } } //else do nothing. Item is already on the list. } /** If the argument indicates a position on the list, the entry at that specified position is returned; otherwise, null is returned. */ public String getEntryAt (int position) { String result = null; if ((1 <= position) && (position <= countOfEntries)) result = entry [position - 1]; return result; } /** Returns true if position indicates the last item on the list; otherwise, returns false. */ public boolean atLastEntry (int position) { return position == countOfEntries; } /** Returns true if item is on the list; otherwise, returns false. Does not differentiate between uppercase and lowercase letters. */ public boolean isOnList (String item) { boolean found = false; int i = 0; while (!found && (i < countOfEntries)) { if (item.equalsIgnoreCase (entry [i])) found = true; else i++; } return found; } public int getMaximumNumberOfEntries () { return entry.length; } public int getNumberOfEntries () { return countOfEntries; } public void eraseList () { countOfEntries = 0; } } |
Listing 7.10 |
/** Class for sorting an array of base type int from smallest to largest. */ public class ArraySorter { /** Precondition: Every element in anArray has a value. Action: Sorts the array into ascending order. */ public static void selectionSort (int [] anArray) { for (int index = 0 ; index < anArray.length - 1 ; index++) { // Place the correct value in anArray[index] int indexOfNextSmallest = getIndexOfSmallest (index, anArray); interchange (index, indexOfNextSmallest, anArray); //Assertion:anArray[0] <= anArray[1] <=...<= anArray[index] //and these are the smallest of the original array elements. //The remaining positions contain the rest of the original //array elements. } } /** Returns the index of the smallest value in the portion of the array that begins at the element whose index is startIndex and ends at the last element. */ private static int getIndexOfSmallest (int startIndex, int [] a) { int min = a [startIndex]; int indexOfMin = startIndex; for (int index = startIndex + 1 ; index < a.length ; index++) { if (a [index] < min) { min = a [index]; indexOfMin = index; //min is smallest of a[startIndex] through a[index] } } return indexOfMin; } /** Precondition: i and j are valid indices for the array a. Postcondition: Values of a[i] and a[j] have been interchanged. */ private static void interchange (int i, int j, int [] a) { int temp = a [i]; a [i] = a [j]; a [j] = temp; //original value of a[i] } } |
Listing 7.11 |
public class SelectionSortDemo
{
public static void main (String [] args)
{
int [] b = {7, 5, 11, 2, 16, 4, 18, 14, 12, 30};
display (b, before);
ArraySorter.selectionSort (b);
display (b, after);
}
public static void display (int [] array, String when)
{
System.out.println ("Array values " + when + " sorting:");
for (int i = 0 ; i < array.length ; i++)
System.out.print (array [i] + " ");
System.out.println ();
}
}
|
Listing 7.12 |
/** Displays a two-dimensional table showing how interest rates affect bank balances. */ public class InterestTable { public static void main (String [] args) { int [] [] table = new int [10] [6]; for (int row = 0 ; row < 10 ; row++) for (int column = 0 ; column < 6 ; column++) table [row] [column] = getBalance (1000.00, row + 1, (5 + 0.5 * column)); System.out.println ("Balances for Various Interest Rates " + "Compounded Annually"); System.out.println ("(Rounded to Whole Dollar Amounts)"); System.out.println (); System.out.println ("Years 5.00% 5.50% 6.00% 6.50% 7.00% 7.50%"); for (int row = 0 ; row < 10 ; row++) { System.out.print ((row + 1) + " "); for (int column = 0 ; column < 6 ; column++) System.out.print ("$" + table [row] [column] + " "); System.out.println (); } } /** Returns the balance in an account after a given number of years and interest rate with an initial balance of startBalance. Interest is compounded annually. The balance is rounded to a whole number. */ public static int getBalance (double startBalance, int years, double rate) { double runningBalance = startBalance; for (int count = 1 ; count <= years ; count++) runningBalance = runningBalance * (1 + rate / 100); return (int) (Math.round (runningBalance)); } } |
Listing 7.13 |
/** Displays a two-dimensional table showing how interest rates affect bank balances. */ public class InterestTable2 { public static final int ROWS = 10; public static final int COLUMNS = 6; public static void main (String [] args) { int [] [] table = new int [ROWS] [COLUMNS]; for (int row = 0 ; row < ROWS ; row++) for (int column = 0 ; column < COLUMNS ; column++) table [row] [column] = getBalance (1000.00, row + 1, (5 + 0.5 * column)); System.out.println ("Balances for Various Interest Rates " + "Compounded Annually"); System.out.println ("(Rounded to Whole Dollar Amounts)"); System.out.println (); System.out.println ("Years 5.00% 5.50% 6.00% 6.50% 7.00% 7.50%"); showTable (table); } /** Precondition: The array anArray has ROWS rows and COLUMNS columns. Postcondition: The array contents are displayed with dollar signs. */ public static void showTable (int [] [] anArray) { for (int row = 0 ; row < ROWS ; row++) { System.out.print ((row + 1) + " "); for (int column = 0 ; column < COLUMNS ; column++) System.out.print ("$" + anArray [row] [column] + " "); System.out.println (); } } public static int getBalance (double startBalance, int years, double rate) { double runningBalance = startBalance; for (int count = 1 ; count <= years ; count++) runningBalance = runningBalance * (1 + rate / 100); return (int) (Math.round (runningBalance)); } } |
Listing 7.14 |
/** Class that records the time worked by each of a companys employees during one five-day week. A sample application is in the main method. */ public class TimeBook { private int numberOfEmployees; private int [] [] hours; //hours[i][j] has the hours for //employee j on day i. private int [] weekHours; //weekHours[i] has the weeks //hours worked for employee i + 1. private int [] dayHours; //dayHours[i] has the total hours //worked by all employees on day i. private static final int NUMBER_OF_WORKDAYS = 5; private static final int MON = 0; private static final int TUE = 1; private static final int WED = 2; private static final int THU = 3; private static final int FRI = 4; /** Reads hours worked for each employee on each day of the work week into the two-dimensional array hours. (The method for input is just a stub in this preliminary version.) Computes the total weekly hours for each employee and the total daily hours for all employees combined. */ public static void main (String [] args) { private static final int NUMBER_OF_EMPLOYEES = 3; TimeBook book = new TimeBook (NUMBER_OF_EMPLOYEES); book.setHours (); book.update (); book.showTable (); } public TimeBook (int theNumberOfEmployees) { numberOfEmployees = theNumberOfEmployees; hours = new int [NUMBER_OF_WORKDAYS] [numberOfEmployees]; weekHours = new int [numberOfEmployees]; dayHours = new int [NUMBER_OF_WORKDAYS]; } public void setHours () //This is a stub. { hours [0] [0] = 8; hours [0] [1] = 0; hours [0] [2] = 9; hours [1] [0] = 8; hours [1] [1] = 0; hours [1] [2] = 9; hours [2] [0] = 8; hours [2] [1] = 8; hours [2] [2] = 8; hours [3] [0] = 8; hours [3] [1] = 8; hours [3] [2] = 4; hours [4] [0] = 8; hours [4] [1] = 8; hours [4] [2] = 8; } public void update () { computeWeekHours (); computeDayHours (); } private void computeWeekHours () { for (employeeNumber = 1 ; employeeNumber <= numberOfEmployees ; employeeNumber++) { //Process one employee: int sum = 0; for (int day = MON ; day <= FRI ; day++) sum = sum + hours [day] [employeeNumber - 1]; //sum contains the sum of all the hours worked in //one week by the employee with number employeeNumber. weekHours [employeeNumber - 1] = sum; } } private void computeDayHours () { for (int day = MON ; day <= FRI ; day++) { //Process one day (for all employees): int sum = 0; for (int employeeNumber = 1 ; employeeNumber <= numberOfEmployees ; employeeNumber++) sum = sum + hours [day] [employeeNumber - 1]; //sum contains the sum of all hours worked by all //employees on one day. dayHours [day] = sum; } } public void showTable () { // heading System.out.print ("Employee "); for (int employeeNumber = 1 ; employeeNumber <= numberOfEmployees ; employeeNumber++) System.out.print (employeeNumber + " "); System.out.println ("Totals"); System.out.println (); // row entries for (int day = MON ; day <= FRI ; day++) { System.out.print (getDayName (day) + " "); for (int column = 0 ; column < hours [day].length ; column++) System.out.print (hours [day] [column] + " "); System.out.println (dayHours [day]); } System.out.println (); System.out.print ("Total = "); for (int column = 0 ; column < numberOfEmployees ; column++) System.out.print (weekHours [column] + " "); System.out.println (); } //Converts 0 to "Monday", 1 to "Tuesday", etc. //Blanks are inserted to make all strings the same length. private String getDayName (int day) { String dayName = null; switch (day) { case MON: dayName = "Monday "; break; case TUE: dayName = "Tuesday "; break; case WED: dayName = "Wednesday"; break; case THU: dayName = "Thursday "; break; case FRI: dayName = "Friday "; break; default: System.out.println ("Fatal Error."); System.exit (0); break; } return dayName; } } |
Listing 7.15 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.HBox; import javafx.scene.control.Button; /** Simple demonstration of adding buttons using the HBox layout. These buttons do not do anything. That comes in a later version. */ public class HBoxDemo extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { HBox root = new HBox(); root.getChildren().add(new Button("This is Button 1")); root.getChildren().add(new Button("This is Button 2")); root.getChildren().add(new Button("This is Button 3")); Scene scene = new Scene(root, 250, 100); primaryStage.setTitle("HBox Demo"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 7.16 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.StackPane; import javafx.scene.control.Label; import javafx.scene.text.Font; /** Simple demonstration of drawing two letters on top of each other using the StackPane layout. */ public class StackPaneDemo extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { StackPane root = new StackPane(); Label label1 = new Label("o"); label1.setFont(Font.font("Courier New", 54)); Label label2 = new Label("c"); label2.setFont(Font.font("Courier New", 24)); root.getChildren().add(label1); root.getChildren().add(label2); Scene scene = new Scene(root, 300, 100); primaryStage.setTitle("StackPane Demo"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 7.17 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.FlowPane; import javafx.scene.control.Button; /** Simple demonstration of adding buttons to the FlowPane layout. */ public class FlowPaneDemo extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { FlowPane root = new FlowPane(); // Set a gap of 5 pixels vertically and horizontally // between buttons root.setVgap(5); root.setHgap(5); root.getChildren().add(new Button("This is Button 1")); root.getChildren().add(new Button("This is Button 2")); root.getChildren().add(new Button("This is Button 3")); Scene scene = new Scene(root, 500, 200); primaryStage.setTitle("FlowPane Demo"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 7.18 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.GridPane; import javafx.geometry.HPos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.geometry.Insets; /** Simple demonstration of adding buttons and labels to the GridPane layout. */ public class GridPaneDemo extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { GridPane root = new GridPane(); // Set a gap of 5 pixels vertically and horizontally // between elements root.setVgap(5); root.setHgap(5); // Margins around the top, right, bottom, and left root.setPadding(new Insets(10,10,10,10)); // Add three nodes, by default horizontally left-aligned root.add(new Label("Option 1"),0,0); root.add(new Button("This is Button 1"),1,0); root.add(new Label("Option 2"),0,1); // Add a button that is horizontally right-aligned Button btn2 = new Button("Button 2"); GridPane.setHalignment(btn2, HPos.RIGHT); root.add(btn2,1,1); // Add a label to the bottom right of the buttons root.add(new Label("Out there"),2,2); Scene scene = new Scene(root, 500, 200); primaryStage.setTitle("GridPane Demo"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 7.19 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.BorderPane; import javafx.scene.control.Button; /** Simple demonstration of adding buttons to the BorderPane layout. */ public class BorderPaneDemo extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { BorderPane root = new BorderPane(); root.setTop(new Button("Top Button")); root.setLeft(new Button("Left Button")); root.setCenter(new Button("Center Button")); root.setRight(new Button("Right Button")); root.setBottom(new Button("Bottom Button")); Scene scene = new Scene(root, 500, 200); primaryStage.setTitle("BorderPane Demo"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 7.20 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.FlowPane; import javafx.scene.control.TextField; import javafx.scene.control.TextArea; import javafx.scene.control.Label; /** Demonstration of TextField and TextArea controls. */ public class TextControlDemo extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { FlowPane root = new FlowPane(); root.setVgap(5); root.setHgap(5); // Label and textfield for name root.getChildren().add(new Label("Name")); TextField txtName = new TextField("Enter name."); txtName.setPrefWidth(100); root.getChildren().add(txtName); // Label and textarea for info root.getChildren().add(new Label("Your Info")); TextArea txtInfo = new TextArea( "Enter some information\nabout yourself."); txtInfo.setPrefWidth(200); txtInfo.setPrefRowCount(4); txtInfo.setPrefColumnCount(40); root.getChildren().add(txtInfo); Scene scene = new Scene(root, 450, 150); primaryStage.setTitle("Text Control Demo"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 7.21 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.FlowPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.control.TextField; import javafx.scene.control.TextArea; import javafx.scene.control.Label; import javafx.scene.control.Button; /** Embedding an HBox and FlowPane into a BorderPane. */ public class CombinedLayout extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { BorderPane root = new BorderPane(); // Create a FlowPane with a TextField and TextArea FlowPane centerPane = new FlowPane(); centerPane.setVgap(5); centerPane.setHgap(5); // Label and textfield for name centerPane.getChildren().add(new Label("Name")); TextField txtName = new TextField("Enter name."); txtName.setPrefWidth(100); centerPane.getChildren().add(txtName); // Label and textarea for info centerPane.getChildren().add(new Label("Your Info")); TextArea txtInfo = new TextArea( "Enter some information\nabout yourself."); txtInfo.setPrefWidth(200); txtInfo.setPrefRowCount(8); txtInfo.setPrefColumnCount(40); centerPane.getChildren().add(txtInfo); // Create an HBox with four buttons HBox topPane = new HBox(); topPane.getChildren().add(new Button("This is Button 1")); topPane.getChildren().add(new Button("This is Button 2")); topPane.getChildren().add(new Button("This is Button 3")); topPane.getChildren().add(new Button("This is Button 4")); // Add the FlowPane to the center root.setCenter(centerPane); // Add the HBox to the top root.setTop(topPane); Scene scene = new Scene(root, 450, 250); primaryStage.setTitle("Text Control Demo"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 7.22 |
import javafx.application.Application; import javafx.scene.canvas.Canvas; import javafx.scene.Scene; import javafx.scene.Group; import javafx.stage.Stage; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; public class PolygonDemo extends Application { private double[] xHouse = {150, 150, 200, 250, 250}; private double[] yHouse = {100, 40, 20, 40, 100}; private double[] xDoor = {175, 175, 200, 200}; private double[] yDoor = {100, 60, 60, 100}; private double[] xWindow = {220, 220, 240, 240}; private double[] yWindow = {60, 80, 80, 60}; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Group root = new Group(); Scene scene = new Scene(root); Canvas canvas = new Canvas(400, 150); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.GREEN); gc.fillPolygon(xHouse, yHouse, xHouse.length); gc.setFill(Color.BLACK); gc.strokePolyline(xDoor, yDoor, xDoor.length); gc.strokePolygon(xWindow, yWindow, xWindow.length); root.getChildren().add(canvas); primaryStage.setTitle("Home sweet home!"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 8.1 |
public class Person { private String name; public Person () { name = "No name yet"; } public Person (String initialName) { name = initialName; } public void setName (String newName) { name = newName; } public String getName () { return name; } public void writeOutput () { System.out.println ("Name: " + name); } public boolean hasSameName (Person otherPerson) { return this.name.equalsIgnoreCase (otherPerson.name); } } |
Listing 8.2 |
public class Student extends Person { private int studentNumber; public Student () { super (); studentNumber = 0; //Indicating no number yet } public Student (String initialName, int initialStudentNumber) { super (initialName); studentNumber = initialStudentNumber; } public void reset (String newName, int newStudentNumber) { setName (newName); studentNumber = newStudentNumber; } public int getStudentNumber () { return studentNumber; } public void setStudentNumber (int newStudentNumber) { studentNumber = newStudentNumber; } public void writeOutput () { System.out.println ("Name: " + getName ()); System.out.println ("Student Number: " + studentNumber); } public boolean equals (Student otherStudent) { return this.hasSameName (otherStudent) && (this.studentNumber == otherStudent.studentNumber); } } |
Listing 8.3 |
public class InheritanceDemo { public static void main (String [] args) { Student s = new Student (); s.setName ("Warren Peace"); s.setStudentNumber (1234); s.writeOutput (); } } |
Listing 8.4 |
public class Undergraduate extends Student { private int level; //1 for freshman, 2 for sophomore, //3 for junior, or 4 for senior. public Undergraduate () { super (); level = 1; } public Undergraduate (String initialName, int initialStudentNumber, int initialLevel) { super (initialName, initialStudentNumber); setLevel (initialLevel); //Checks 1 <= initialLevel <= 4 } public void reset (String newName, int newStudentNumber, int newLevel) { reset (newName, newStudentNumber); //Students reset setLevel (newLevel); //Checks 1 <= newLevel <= 4 } public int getLevel () { return level; } public void setLevel (int newLevel) { if ((1 <= newLevel) && (newLevel <= 4)) level = newLevel; else { System.out.println ("Illegal level!"); System.exit (0); } } public void writeOutput () { super.writeOutput (); System.out.println ("Student Level: " + level); } public boolean equals (Undergraduate otherUndergraduate) { return equals ((Student) otherUndergraduate) && (this.level == otherUndergraduate.level); } } |
Listing 8.5 |
public boolean equals (Object otherObject)
{
boolean isEqual = false;
if ((otherObject != null) &&
(otherObject instanceof Student))
{
Student otherStudent = (Student) otherObject;
isEqual = this.sameName (otherStudent) &&
(this.studentNumber ==
otherStudent.studentNumber);
}
return isEqual;
}
|
Listing 8.6 |
public class PolymorphismDemo { public static void main(String[] args) { Person[] people = new Person[4]; people[0] = new Undergraduate("Cotty, Manny", 4910, 1); people[1] = new Undergraduate("Kick, Anita", 9931, 2); people[2] = new Student("DeBanque, Robin", 8812); people[3] = new Undergraduate("Bugg, June", 9901, 4); for (Person p : people) { p.writeOutput(); System.out.println(); } } } |
Listing 8.7 |
/** An interface for methods that return the perimeter and area of an object. */ public interface Measurable { /** Returns the perimeter. */ public double getPerimeter (); /** Returns the area. */ public double getArea (); } |
Listing 8.8 |
/** A class of rectangles. */ public class Rectangle implements Measurable { private double myWidth; private double myHeight; public Rectangle (double width, double height) { myWidth = width; myHeight = height; } public double getPerimeter () { return 2 * (myWidth + myHeight); } public double getArea () { return myWidth * myHeight; } } |
Listing 8.9 |
/** A class of circles. */ public class Circle implements Measurable { private double myRadius; public Circle (double radius) { myRadius = radius; } public double getPerimeter () { return 2 * Math.PI * myRadius; } public double getCircumference () { return getPerimeter (); } public double getArea () { return Math.PI * myRadius * myRadius; } } |
Listing 8.10 |
/** Interface for simple shapes drawn on the screen using keyboard characters. */ public interface ShapeInterface { /** Sets the offset for the shape. */ public void setOffset (int newOffset); /** Returns the offset for the shape. */ public int getOffset (); /** Draws the shape at lineNumber lines down from the current line. */ public void drawAt (int lineNumber); /** Draws the shape at the current line. */ public void drawHere (); } |
Listing 8.11 |
/** Interface for a rectangle to be drawn on the screen. */ public interface RectangleInterface extends ShapeInterface { /** Sets the rectangle's dimensions. */ public void set (int newHeight, int newWidth); } /** Interface for a triangle to be drawn on the screen. */ public interface TriangleInterface extends ShapeInterface { /** Sets the triangle's base. */ public void set (int newBase); } |
Listing 8.12 |
/** Class for drawing simple shapes on the screen using keyboard characters. This class will draw an asterisk on the screen as a test. It is not intended to create a "real" shape, but rather to be used as a base class for other classes of shapes. */ public class ShapeBasics implements ShapeInterface { private int offset; public ShapeBasics () { offset = 0; } public ShapeBasics (int theOffset) { offset = theOffset; } public void setOffset (int newOffset) { offset = newOffset; } public int getOffset () { return offset; } public void drawAt (int lineNumber) { for (int count = 0 ; count < lineNumber ; count++) System.out.println (); drawHere (); } public void drawHere () { for (int count = 0 ; count < offset ; count++) System.out.print (' '); System.out.println ('*'); } } |
Listing 8.13 |
/** Class for drawing rectangles on the screen using keyboard characters. Each character is higher than it is wide, so these rectangles will look taller than you might expect. Inherits getOffset, setOffset, and drawAt from the class ShapeBasics. */ public class Rectangle extends ShapeBasics implements RectangleInterface { private int height; private int width; public Rectangle () { super (); height = 0; width = 0; } public Rectangle (int theOffset, int theHeight, int theWidth) { super (theOffset); height = theHeight; width = theWidth; } public void set (int newHeight, int newWidth) { height = newHeight; width = newWidth; } public void drawHere () { drawHorizontalLine (); drawSides (); drawHorizontalLine (); } private void drawHorizontalLine () { skipSpaces (getOffset ()); for (int count = 0 ; count < width ; count++) System.out.print ('-'); System.out.println (); } private void drawSides () { for (int count = 0 ; count < (height - 2) ; count++) drawOneLineOfSides (); } private void drawOneLineOfSides () { skipSpaces (getOffset ()); System.out.print ('|'); skipSpaces (width - 2); System.out.println ('|'); } //Writes the indicated number of spaces. private static void skipSpaces (int number) { for (int count = 0 ; count < number ; count++) System.out.print (' '); } } |
Listing 8.14 |
/** Class for drawing triangles on the screen using keyboard characters. A triangle points up. Its size is determined by the length of its base, which must be an odd integer. Inherits getOffset, setOffset, and drawAt from the class ShapeBasics. */ public class Triangle extends ShapeBasics implements TriangleInterface { private int base; public Triangle () { super (); base = 0; } public Triangle (int theOffset, int theBase) { super (theOffset); base = theBase; } /** Precondition: newBase is odd. */ public void set (int newBase) { base = newBase; } public void drawHere () { drawTop (); drawBase (); } private void drawBase () { skipSpaces (getOffset ()); for (int count = 0 ; count < base ; count++) System.out.print ('*'); System.out.println (); } { //startOfLine == number of spaces to the //first '*' on a line. Initially set to the //number of spaces before the topmost '*'. int startOfLine = getOffset () + base / 2; skipSpaces (startOfLine); System.out.println ('*'); //top '*' int lineCount = base / 2 - 1; //height above base //insideWidth == number of spaces between the //two '*'s on a line. int insideWidth = 1; for (int count = 0 ; count < lineCount ; count++) { //Down one line, so the first '*' is one more //space to the left. startOfLine--; skipSpaces (startOfLine); System.out.print ('*'); skipSpaces (insideWidth); System.out.println ('*'); //Down one line, so the inside is 2 spaces wider. insideWidth = insideWidth + 2; } } private static void skipSpaces (int number) { for (int count = 0 ; count < number ; count++) System.out.print (' '); } } |
Listing 8.15 |
/** A program that draws a fir tree composed of a triangle and a rectangle, both drawn using keyboard characters. */ public class TreeDemo { public static final int INDENT = 5; public static final int TREE_TOP_WIDTH = 21; // must be odd public static final int TREE_BOTTOM_WIDTH = 4; public static final int TREE_BOTTOM_HEIGHT = 4; public static void main (String [] args) { drawTree (TREE_TOP_WIDTH, TREE_BOTTOM_WIDTH, TREE_BOTTOM_HEIGHT); } public static void drawTree (int topWidth, int bottomWidth, int bottomHeight) { System.out.println (" Save the Redwoods!"); TriangleInterface treeTop = new Triangle (INDENT, topWidth); drawTop (treeTop); RectangleInterface treeTrunk = new Rectangle (INDENT + (topWidth / 2) - (bottomWidth / 2), bottomHeight, bottomWidth); drawTrunk (treeTrunk); } private static void drawTop (TriangleInterface treeTop) { treeTop.drawAt (1); } private static void drawTrunk (RectangleInterface treeTrunk) { treeTrunk.drawHere (); // or treeTrunk.drawAt(0); } } |
Listing 8.16 |
public class Fruit { private String fruitName; public Fruit() { fruitName = ""; } public Fruit(String name) { fruitName = name; } public void setName(String name) { fruitName = name; } public String getName() { return fruitName; } } |
Listing 8.17 |
import java.util.Arrays; public class FruitDemo { public static void main(String[] args) { Fruit[] fruits = new Fruit[4]; fruits[0] = new Fruit("Orange"); fruits[1] = new Fruit("Apple"); fruits[2] = new Fruit("Kiwi"); fruits[3] = new Fruit("Durian"); Arrays.sort(fruits); // Output the sorted array of fruits for (Fruit f : fruits) { System.out.println(f.getName()); } } } |
Listing 8.18 |
public class Fruit implements Comparable { private String fruitName; public Fruit() { fruitName = ""; } public Fruit(String name) { fruitName = name; } public void setName(String name) { fruitName = name; } public String getName() { return fruitName; } public int compareTo(Object o) { if ((o != null) && (o instanceof Fruit)) { Fruit otherFruit = (Fruit) o; return (fruitName.compareTo(otherFruit.fruitName)); /*** Alternate definition of comparison using fruit length ***/ /* if (fruitName.length() > otherFruit.fruitName.length()) return 1; else if (fruitName.length() < otherFruit.fruitName.length()) return -1; else return 0; */ } return -1; // Default if other object is not a Fruit } } |
Listing 8.19 |
/** Abstract base class for drawing simple shapes on the screen using characters. */ public abstract class ShapeBase implements ShapeInterface { private int offset; public abstract void drawHere (); /* The rest of the class is identical to ShapeBasics in Listing 8.11, except for the names of the constructors.Only the method drawHere is abstract. Methods other than drawHere have bodies and do not have the keyword abstract in heir headings. We repeat one such method here: */ public void drawAt (int lineNumber) { for (int count = 0 ; count < lineNumber ; count++) System.out.println (); drawHere (); } } |
Listing 8.20 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.VBox; import javafx.scene.control.Button; /** Simple demonstration of programming buttons in a JavaFX application. This version outputs a message when clicked. */ public class ButtonDemo1 extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { VBox root = new VBox(); Button btnSunny; Button btnCloudy; btnSunny = new Button("Sunny"); btnCloudy = new Button("Cloudy"); // Create an event object to handle the button click. // The "handle" method in HandleButtonClick will be // invoked when the button is clicked. HandleButtonClick clickEvent = new HandleButtonClick(); btnSunny.setOnAction(clickEvent); // We can also create the HandleButtonClick object without // a named reference by creating it inside the call to setOnAction btnCloudy.setOnAction(new HandleButtonClick("It is cloudy.")); root.getChildren().add(btnSunny); root.getChildren().add(btnCloudy); Scene scene = new Scene(root, 300, 100); primaryStage.setTitle("Button Event Handling Demo"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 8.21 |
import javafx.event.ActionEvent; import javafx.event.EventHandler; /** This class handles a button click and outputs a message. The handle method is invoked when the button is clicked. */ public class HandleButtonClick implements EventHandler<ActionEvent> { private String message; public HandleButtonClick() { message = "It is sunny!"; } public HandleButtonClick(String customMessage) { message = customMessage; } @Override public void handle(ActionEvent event) { System.out.println(message); } } |
Listing 8.22 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.VBox; import javafx.scene.control.Button; import javafx.event.ActionEvent; import javafx.event.EventHandler; /** Demonstration of event handling within the ButtonDemo2 class. */ public class ButtonDemo2 extends Application implements EventHandler<ActionEvent> { private Button btnSunny; private Button btnCloudy; public static void main(String[] args) { launch(args); } @Override public void handle(ActionEvent event) { // This method can access the member variables // which reference the other GUI controls if (event.getSource() instanceof Button) { Button btnClicked = (Button) event.getSource(); if (btnClicked.getText().equals("Sunny")) { // Disable the cloudy button if sunny clicked btnCloudy.setDisable(true); } else if (btnClicked.getText().equals("Cloudy")) { // Disable the sunny button if cloudy clicked btnSunny.setDisable(true); } } } @Override public void start(Stage primaryStage) throws Exception { VBox root = new VBox(); btnSunny = new Button("Sunny"); btnCloudy = new Button("Cloudy"); btnSunny.setOnAction(this); btnCloudy.setOnAction(this); root.getChildren().add(btnSunny); root.getChildren().add(btnCloudy); Scene scene = new Scene(root, 300, 100); primaryStage.setTitle("Button Demo 2"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 8.23 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.layout.VBox; import javafx.scene.control.Button; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.control.Label; /** Event handling with an anonymous inner class. */ public class ButtonDemo3 extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { VBox root = new VBox(); Button btnSunny; Button btnCloudy; Label lblMessage; btnSunny = new Button("Sunny"); btnCloudy = new Button("Cloudy"); lblMessage = new Label("Click a button."); // Create an anonymous inner class to handle btnSunny btnSunny.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { lblMessage.setText("It is sunny!"); } } ); // Create an anonymous inner class to handle btnCloudy btnCloudy.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { lblMessage.setText("It is cloudy!"); } } ); root.getChildren().add(btnSunny); root.getChildren().add(btnCloudy); root.getChildren().add(lblMessage); Scene scene = new Scene(root, 300, 100); primaryStage.setTitle("Button Demo 3"); primaryStage.setScene(scene); primaryStage.show(); } } |
Listing 8.24 |
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.layout.GridPane; import javafx.scene.layout.BorderPane; import javafx.scene.control.TextField; import javafx.scene.control.Label; import javafx.scene.control.Button; import javafx.geometry.Insets; import javafx.event.ActionEvent; import javafx.event.EventHandler; /** This application embeds a GridPane in the center of a BorderPane. It allows the user to enter numbers into text fields which are added together in the button click event. The sum is displayed in a label in the bottom region of the BorderPane. */ public class AddingNumbersApp extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { BorderPane root = new BorderPane(); // Margin of 10 pixels root.setPadding(new Insets(10,10,10,10)); Button btnAdd; TextField txtNum1, txtNum2; Label lblSum; // Add a label message in the top. We create the // label without a named reference since the label // is read-only; we never change it so no reference is needed. root.setTop(new Label("Enter an integer into each textbox " + "and click the button to compute the sum.")); // The label that will display the sum goes into the bottom. // Initially it is just a blank string. lblSum = new Label(""); root.setBottom(lblSum); // Create a GridPane in the center of the BorderPane GridPane center = new GridPane(); center.setVgap(5); center.setHgap(5); txtNum1 = new TextField("0"); // Default text of 0 txtNum1.setPrefWidth(150); txtNum2 = new TextField("0"); txtNum2.setPrefWidth(150); center.add(new Label("Number 1"), 0, 0); center.add(new Label("Number 2"), 0, 1); center.add(txtNum1, 1, 0); center.add(txtNum2, 1, 1); btnAdd = new Button("Add Numbers"); center.add(btnAdd, 1, 2); root.setCenter(center); // Set the event handler when the button is clicked btnAdd.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { int num1 = Integer.parseInt(txtNum1.getText()); int num2 = Integer.parseInt(txtNum2.getText()); int sum = num1 + num2; lblSum.setText("The sum is " + sum); } } ); Scene scene = new Scene(root, 450, 150); primaryStage.setTitle("Compute the Sum"); primaryStage.setScene(scene); primaryStage.show(); } } |