Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the inventory management application of Project 6. A solution to this p

ID: 3829510 • Letter: C

Question

Consider the inventory management application of Project 6. A solution to this project is given at the end of this document. You can use this code or your own code in Project 6 as a basis for this assignment. Either way is fine.

For the fixed part of this project (the 220 points) you must extend the program as follows:

Add a delete command.

Keep the inventory in alphabetical order.   When a new item is to be added, put the entry into the appropriate location in the array.

Construct a Graphical User Interface (GUI) for the user. Do not use JOptionPane. You must use JavaFX.

Make the program object oriented. This means having a separate class for the internal representation of the inventory, with methods like add, list, or delete. It also means having a separate class for the GUI aspects of the program.

The program must follow the 10 Program Standards given with Project 4 (all previous projects are still posted in the folder “Previous Projects”). These standards are reposted in a file called

            Program Standards for Java Course.doc

For the optional part of this project you may extend the program in various ways. Some areas for extension are as follows:

Usability and Aesthetics: Make the GUI especially pleasing to see and use. One example would be to make the list command give a nice listing.

Human Engineering: Provide good human engineering for the user. This means being very tolerant of user errors and making it easy to use. For example, you might give the user an option to name the inventory file, or you might check if the user tries to add another entry with the same name. Also, consider a simple Help command.

Reliability: Make the program especially reliable. Try to make it so that the program will not crash even under incorrect inputs. For example, handle a missing file well or prevent an array out of bounds error.

Maintainability: Make the program especially well structured and readable.

Functionality: Enhance to functionality of the program in various ways, even small ways.

For functionality, one enhancement would be to check that a find or enter command actually has a non-null string for the name. A little more work would be to check the validity of an item’s quantity. For instance, always verifying that an item’s quantity is greater than or equal to zero. An obvious enhancement could be a delete command.

For another example, one could allow a partial match to find or delete an entry. For example, “F po” would match any entry with “pop” in the name, for example “Pop” or “Popcorn” or “Potato”. You might use the function “find” in C++ for this feature.

Final Submission:   Submitting a portfolio or dossier of sorts (a stapled or bound set of pages) containing

A separate cover page (or pages) itemizing the grounds for extra credit. It is your responsibility to itemize all grounds for extra credit.

A printout of your code,

A printout from several consecutive runs, illustrating the various features of your program. For example, you must show that the file I/O works.

A printout from the list command

In the sample runs, each of the commands "e", "f", "l", “d”, and "q" should be illustrated.

A solution similar to Project 6.

import java.io.*;

import java.util.*;

class Entry {

       public String name, quantity, note;

}

public class InventoryFor1510 {

   public static Entry[] entryList;

   public static int     num_entries;

   public static Scanner stdin = new Scanner(System.in);

public static void main(String args[]) throws Exception{

       int i;

char C;

       String code, Command;

       entryList = new Entry[200];

       num_entries = 0;

       Command = null;

       C = ' ';

       readInventory("inventory.txt");

      

       System.out.println("Codes are entered as 1 to 8 characters. Use" +

                     " "e" for enter," +

                     " "f" for find," +

                     " "l" for listing all the entries," +

                     " "q" to quit.");

      

       while(C != 'q'){

              System.out.print("Command: ");

              Command = stdin.next();

              C = Command.charAt(0);                         

              switch (C) {

              case 'e':

addItem(); break;

              case 'f':

                     code = stdin.next();

                     stdin.nextLine();

                     i = index(code);

                     if (i >= 0) displayEntry(entryList [i]);

                     else       System.out.println("**No entry with code " + code); break;           

              case 'l':

                     listAllItems(); break;           

              case 's':

                     sortList(); break;        

              case 'q':

                     CopyInventoryToFile("inventory.txt");

                     System.out.println("Quitting the application. All the entries are "

                                  + "stored in the file inventory.txt"); break;         

              default:

                     System.out.println("Invalid command. Please enter the command again!!!");                      }

       }

}

public static void readInventory(String FileName) throws Exception {

       File F;

       F = new File(FileName);         

       Scanner S = new Scanner(F);                    

      

       while (S.hasNextLine()) {

              entryList [num_entries]= new Entry();

              entryList [num_entries].name   = S.next();

              entryList [num_entries].quantity = S.next();

              entryList [num_entries].note   = S.nextLine();

              num_entries++;

       }

       S.close();          

}

public static void addItem() {

       String name = stdin.next();

       String quantity;

       stdin.nextLine();

       entryList [num_entries]      = new Entry();

       entryList [num_entries].name = name;

      

       System.out.print("Enter Quantity: ");

       quantity = stdin.nextLine();

       entryList [num_entries].quantity = quantity;

             

       System.out.print("Enter Notes: ");

       entryList [num_entries].note = stdin.nextLine();

       num_entries++;

}

      

public static int index(String Key) {

// Function to get the index of a key from an array

// if not found, returns -1

       for (int i=0; i < num_entries; i++) {

              if (entryList [i].name.equalsIgnoreCase(Key))

                           return i; // Found the Key, return index.

       }

       return -1;

}

public static void displayEntry(Entry item) {

       System.out.println("--"+ item.name+" "+

                        item.quantity+" "+

                        item.note);

}

public static void listAllItems() {

       int i = 0;

       while (i < num_entries) {

              displayEntry(entryList [i]);

              i++;

       }

}

public static void CopyInventoryToFile(String FileName) throws Exception{

       FileOutputStream out = new FileOutputStream(FileName);

       PrintStream P        = new PrintStream( out );

                           

       for (int i=0; i < num_entries; i++) {

              P.println(entryList [i].name + " " + entryList [i].number +

                                  " " + entryList [i].note);

       }            

}

}

Explanation / Answer

Current Recommendation

For basic common dialogs like alerts or confirmations, use the built-in dialog functionality in the JavaFX 8u40+ toolkits. Early access release for 8u40 is available and the dialog API there is stable and will map to the projected March 2015 production release.
If you need a specific kind of dialog box, like for tasks such as login, font selection, progress feedback and wizards, use ControlsFX (which supports a greater range of default dialog implementations than the core JavaFX platform).
If you need a completely customized dialog, then use the techniques outlined later in this answer.
Background

Don't reinvent the wheel. Use the ControlsFX library for JOptionPane type dialogs rather than writing your own implementation (and JavaFX 8u40 will introduce common dialog boxes into the platform).

The code you reference for modal dialog display is quite old now. There have been numerous features (including the addition of showAndWait) implemented both in the JavaFX core platform and 3rd party libraries, which mean that if you are doing the task today, it would probably be done in a different way.

The referenced code in the question makes use of Builders which have been deprecated in Java 8, so it is no longer recommended to use them (they no longer even show up in the JavaFX javadoc).

Code Demonstrating the built-in JavaFX 8u40+ Alert class

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class ShowAndWaitBuiltInAlert extends Application {
@Override public void start(Stage stage) {
Button showDialog = new Button("Show Dialog");
showDialog.setOnAction(event -> {
Alert dialog = new Alert(
Alert.AlertType.CONFIRMATION,
"Are you sure you want to exit the Dialog Demo Application?"
);
dialog.showAndWait()
.filter(response -> response.equals(ButtonType.OK))
.ifPresent(response -> stage.close());
});

stage.setScene(new Scene(showDialog));
stage.show();
}

public static void main(String[] args) { launch(args); }
}
An alert extends from Dialog, so it can be customized using all the customization methods of the Dialog class.

Code Demonstrating the built-in JavaFX 8u40+ Dialog class

confirm dialog same

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class ShowAndWaitBuiltInDialog extends Application {
@Override public void start(Stage stage) {
Button showDialog = new Button("Show Dialog");
showDialog.setOnAction(e -> {
Dialog<ButtonType> dialog = new Dialog<>();
dialog.setTitle("Dialog Demo");
dialog.setHeaderText("Confirm Exit");
dialog.setContentText("Are you sure you want to exit the Dialog Demo Application?");
ButtonType exit = new ButtonType("Exit", ButtonBar.ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(
exit, ButtonType.CANCEL
);
dialog.showAndWait()
.filter(response -> response.equals(exit))
.ifPresent(response -> stage.close());
});

stage.setScene(new Scene(showDialog));
stage.show();
}

public static void main(String[] args) { launch(args); }
}
Custom Dialog Code Demonstrating showAndWait

The following code will work in Java 8 versions predating Java 8u40.

dialogsample

import javafx.application.Application;
import javafx.beans.property.*;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;

public class ShowAndWaitDialog extends Application {

public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage stage) {
Button showDialog = new Button("Show Dialog");
showDialog.setOnAction(e -> {
ConfirmationDialog dialog = new ConfirmationDialog(
"Would you like to exit the application?"
);
dialog.setY(stage.getY() + stage.getHeight() + 10);
dialog.setX(stage.getX());
dialog.showAndWait();
if (dialog.isSelected()) {
stage.close();
}
});
stage.setScene(new Scene(showDialog));
stage.show();
}

class ConfirmationDialog extends Stage {
private VBox layout = new VBox();

private ReadOnlyBooleanWrapper selected = new ReadOnlyBooleanWrapper();
public boolean isSelected() {
return selected.get();
}
public ReadOnlyBooleanProperty selectedProperty() {
return selected.getReadOnlyProperty();
}

public ConfirmationDialog(String question) {
initStyle(StageStyle.UTILITY);
initModality(Modality.APPLICATION_MODAL);

layout.setSpacing(10);
layout.setPadding(new Insets(10));

createControls();

layout.getChildren().addAll(
new Label(question),
createControls()
);

setScene(new Scene(layout));
sizeToScene(); // workaround because utility stages aren't automatically sized correctly to their scene.
}

private HBox createControls() {
final Button ok = new Button("OK");
ok.setOnAction(e -> {
selected.set(true);
close();
});

final Button cancel = new Button("Cancel");
cancel.setOnAction(e -> {
selected.set(false);
close();
});

final HBox controls = new HBox(10, ok, cancel);
controls.setAlignment(Pos.CENTER_RIGHT);

return controls;
}
}
}