This program must be done using JavaFX. I have attached an example that can be t
ID: 3663224 • Letter: T
Question
This program must be done using JavaFX. I have attached an example that can be tweaked to make this program, thank you for your help
package hardwarestore;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HardwareStore extends Application {
HardwareFile hFile; // random access hardware file
// Text fields
private TextField tfName = new TextField();
private TextField tfQuantity = new TextField();
private TextField tfPrice = new TextField();
// Buttons
private Button btAdd = new Button("Add");
private Button btFirst = new Button("First");
private Button btNext = new Button("Next");
private Button btPrevious = new Button("Previous");
private Button btLast = new Button("Last");
private Button btUpdate = new Button("Update");
public HardwareStore()
{
// open or create hardware file when application instantiates
try {
hFile = new HardwareFile();
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
}
@Override
public void start(Stage primaryStage) {
GridPane p1 = new GridPane();
p1.setAlignment(Pos.CENTER);
p1.setHgap(5);
p1.setVgap(5);
p1.add(new Label("Name"), 0, 0);
p1.add(new Label("Quantity on Hand"), 0, 1);
p1.add(new Label("Unit Price"), 0, 2);
p1.add(tfName, 1, 0);
p1.add(tfQuantity, 1, 1);
p1.add(tfPrice, 1, 2);
// Add buttons to a pane
HBox p3 = new HBox(5);
p3.getChildren().addAll(btAdd, btFirst, btNext, btPrevious,
btLast, btUpdate);
p3.setAlignment(Pos.CENTER);
// Add p1 and p3 to a border pane
BorderPane borderPane = new BorderPane();
borderPane.setCenter(p1);
borderPane.setBottom(p3);
// Create a scene and place it in the stage
Scene scene = new Scene(borderPane, 350, 120);
primaryStage.setTitle("Hardware Inventory"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
// Display the first record if exists
Hardware hw = hFile.firstHardware();
if(hw != null) setDisplay(hw);
/********* Action Events *************/
btAdd.setOnAction(e -> {
hFile.addHardware(getDisplay());
});
btFirst.setOnAction(e -> {
Hardware item = hFile.firstHardware();
if(item != null) setDisplay(item);
});
btNext.setOnAction(e -> {
Hardware item = hFile.nextHardware();
if (item != null) setDisplay(item);
});
btPrevious.setOnAction(e -> {
Hardware item = hFile.previousHardware();
if (item != null) setDisplay(item);
});
btLast.setOnAction(e -> {
Hardware item = hFile.lastHardware();
if (item != null) setDisplay(item);
});
btUpdate.setOnAction(e -> {
Hardware item = getDisplay();
hFile.updateHardware(item);
});
}
// utility method to put data into display
private void setDisplay(Hardware hw) {
tfName.setText(hw.getName());
tfQuantity.setText(String.format("%d", hw.getQuantity()));
tfPrice.setText(String.format("%.2f", hw.getPrice()));
}
// utility method to get data from display
private Hardware getDisplay() {
Hardware hw = new Hardware();
hw.setName(tfName.getText());
int quantity = Integer.parseInt(tfQuantity.getText());
hw.setQuantity(quantity);
double price = Double.parseDouble(tfPrice.getText());
hw.setPrice(price);
return hw;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
/*
* HardwareFile class
* Represents the random access hardware data file
* presents interace to hardware data file
*/
package hardwarestore;
import java.io.RandomAccessFile;
import java.io.IOException;
public class HardwareFile extends RandomAccessFile
{
public final static int NAME_LENGTH = 32; // number of chars in name
// size of a Java char is two bytes becaule it is Unicode
// thus size is twice length
public final static int NAME_SIZE = 2 * NAME_LENGTH; // number of bytes in name
public final static int QUANTITY_SIZE = 4; // size of integer
public final static int PRICE_SIZE = 8; // size of double
// ture record size
public final static int RECORD_SIZE = NAME_SIZE + QUANTITY_SIZE + PRICE_SIZE;
public HardwareFile() throws IOException
{
// open or create the hardware file on instantiation
super("hardware.dat","rw");
}
public Hardware readHardware(long position) throws IOException {
Hardware rec = new Hardware();
seek(position); // locate and read record
rec.setName(readFixedLengthString(NAME_LENGTH));
rec.setQuantity(readInt());
rec.setPrice(readDouble());
return rec;
}
public void writeHardware(long position, Hardware hItem) {
try {
seek(position); // set position in file
// write recode - name (fixed length) quantity and price
writeFixedLengthString(hItem.getName(),NAME_LENGTH);
writeInt(hItem.getQuantity());
writeDouble(hItem.getPrice());
} catch (IOException ex){
ex.printStackTrace();
}
}
public void addHardware(Hardware item) {
try {
// add new record to end of file
writeHardware(length(), item);
} catch (IOException ex) { }
}
public Hardware firstHardware() {
// return first record in file
Hardware item = null;
try {
if (length() > 0) item = readHardware(0);
} catch (IOException ex) {
item = null;
}
return item;
}
public Hardware lastHardware() {
Hardware item = null;
try {
if (length() > 0) {
item = readHardware(length() - RECORD_SIZE);
}
else return null;
} catch (IOException ex) {
item = null;
}
return item;
}
public Hardware nextHardware() {
Hardware item = null;
try {
long currentPosition = getFilePointer();
if (currentPosition < length()) {
item = readHardware(currentPosition);
}
} catch (IOException ex) {
item = null;
}
return item;
}
public Hardware previousHardware() {
Hardware item = null;
try {
long currentPosition = getFilePointer();
if (currentPosition - RECORD_SIZE > 0)
{
item = readHardware(currentPosition - 2 * RECORD_SIZE);
} else {
item = readHardware(0);
}
} catch (IOException ex) {
item = null;
}
return item;
}
public void updateHardware(Hardware item) {
try {
writeHardware(getFilePointer() - RECORD_SIZE, item);
} catch (IOException ex) { }
}
// utility methods for dealing with fixed length strings
private String readFixedLengthString(int length) throws IOException {
char[] chars = new char[length]; // fixed length char buffer
// read string in a character at a time
for (int i = 0; i < length; i++) chars[i] = readChar();
return new String(chars);
}
private void writeFixedLengthString(String s, int length) throws IOException {
char[] chars = new char[length]; // fixed length char buffer
// load String into char array
s.getChars(0, Math.min(s.length(), length), chars, 0);
// fill in blank chars in rest of array
for (int i = Math.min(s.length(), length); i < chars.length; i++) {
chars[i] = ' ';
}
// write fixed length char array to file
writeChars(new String(chars));
}
}
/*
* Hardware class - Represents an item in the HardwareStore inventory
*/
package hardwarestore;
public class Hardware
{
private String name;
private int quantity;
private double price;
public Hardware() { this("",0,0.0); }
public Hardware( String name, int quantity, double price )
{
setName(name);
setQuantity(quantity);
setPrice(price);
}
public String getName() { return name; }
public void setName( String name ) { this.name = name; }
public int getQuantity() { return quantity; }
public void setQuantity( int quantity ) { this.quantity = quantity > 0 ? quantity : 0; }
public double getPrice() { return price; }
public void setPrice( double price ) { this.price = price > 0.0 ? price : 0.0; }
}
Explanation / Answer
/**
* Address book
*---------------------------
* Write a program that stores, retrieves, adds, and updates addresses .
* fixed-length string for storing .
* Use random access file for reading and writing an address.
* size of name, street, city, state, and zip is 32,
* 32, 20, 2, 5 bytes, respectively.
*/
import ToolKit.Contact;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.io.*;
import java.util.ArrayList;
public class AddressbookLauncher extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
AddressBook addrPane = new AddressBook("/Users/StoreFile/");
primaryStage.setScene(new Scene(addrPane));
primaryStage.setTitle("Address Book");
primaryStage.show();
}
}
class BasicAddressPane extends GridPane {
// Labels
Label lblName;
Label lblStreet;
Label lblCity;
Label lblState;
Label lblZip;
// TextFields
TextField tfName;
TextField tfStreet;
TextField tfCity;
TextField tfState;
TextField tfZip;
BasicAddressPane() {
// Grid pane settings
this.setPadding(new Insets(10));
this.setHgap(10);
this.setVgap(10);
// Create Labels with Textfield
lblName = createComponent("Name:", 0, tfName = new TextField(), 0);
lblStreet = createComponent("Street:", 0, tfStreet = new TextField(), 0);
lblCity = createComponent("City:", 140, tfCity = new TextField(), 100);
lblState = createComponent("State:", 90, tfState = new TextField(), 40);
lblZip = createComponent("Zip:", 130, tfZip = new TextField(), 100);
// add name on first row
this.add(lblName, 0, 0, 5, 1);
tfName.setPrefColumnCount(25);
// add street on second row
this.add(lblStreet, 0, 1, 5, 1);
tfStreet.setPrefColumnCount(25);
// add city, state, zip on third row
HBox hBox = new HBox();
hBox.getChildren().addAll(lblCity, lblState, lblZip);
hBox.setMaxWidth(410);
hBox.setSpacing(5);
this.add(hBox, 0, 2, 5, 1);
}
/**
* @param name - Name of Label
* @param lblWidth - Label max width: 0 = default
* @param textField - TextField to be attached with label
* @param tfWidth - TextField max width: 0 = default
* @return Label
*/
private Label createComponent(String name, double lblWidth, TextField textField, double tfWidth) {
Label label = new Label(name, textField);
label.setContentDisplay(ContentDisplay.RIGHT);
// set textfield and label custom min width if needed
if (lblWidth > 0) {
label.setMaxWidth(lblWidth);
}
if (tfWidth > 0) {
textField.setMaxWidth(tfWidth);
}
return label;
}
protected void setTextFields(String name, String street, String city, String state, String zip) {
tfName.setText(name);
tfStreet.setText(street);
tfCity.setText(city);
tfState.setText(state);
tfZip.setText(zip);
}
}
class AddressBook extends BasicAddressPane {
ArrayList<Contact> contacts;
int index = 0;
// Buttons
Button btnAdd;
Button btnFirst;
Button btnNext;
Button btnPrev;
Button btnLast;
Button btnUpdate;
boolean isNewFile;
String fileName = "AddressBook.dat";
File file;
AddressBook() {
this(System.getProperty("user.dir")); // default path is current working directory
}
AddressBook(String path) {
btnAdd = new Button("Add");
btnFirst = new Button("First");
btnNext = new Button("Next");
btnPrev = new Button("Prev");
btnLast = new Button("Last");
btnUpdate = new Button("Update");
// Init buttons and create bottom button panel
HBox hBox = new HBox(15, btnAdd, btnFirst, btnPrev, btnNext, btnLast, btnUpdate);
hBox.setAlignment(Pos.CENTER);
this.add(hBox, 0, 3, 5, 1);
// create listeners
btnAdd.setOnAction(e -> addContact());
btnUpdate.setOnAction(e -> updateContact());
btnFirst.setOnAction(e -> {
index = 0;
refresh();
});
btnLast.setOnAction(e -> {
index = contacts.size() - 1;
refresh();
});
btnNext.setOnAction(e -> next());
btnPrev.setOnAction(e -> previous());
// Get address book file
file = new File(path + fileName);
// if file doesn't exist, create it
try {
isNewFile = file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (!isNewFile) {
SynchronizationContacts();
} else {
contacts = new ArrayList<>();
}
refresh();
}
private void previous() {
if (index > 0) {
index--;
refresh();
}
}
private void next() {
if (index != contacts.size() - 1) {
index++;
refresh();
}
}
private void refresh() {
if (contacts.isEmpty()) return;
Contact c = contacts.get(index);
setTextFields(
c.getFullName(),
c.getStreet(),
c.getCity(),
c.getState(),
c.getZip()
);
}
public void addContact() {
contacts.add(getCurrentContact());
index = contacts.size() - 1;
refresh();
saveContacts();
}
public void updateContact() {
contacts.remove(index);
contacts.add(index, getCurrentContact());
saveContacts();
}
public Contact getCurrentContact() {
return new Contact(
tfName.getText(),
tfStreet.getText(),
tfCity.getText(),
tfState.getText(),
tfZip.getText()
);
}
/**
* Synchronization contacts with addressbook .
*/
private void SynchronizationContacts() {
// Init new buffer array
contacts = new ArrayList<>();
// Byte array for each field
byte[] name = new byte[32];
byte[] street = new byte[32];
byte[] city = new byte[20];
byte[] state = new byte[2];
byte[] zip = new byte[5];
try (FileInputStream input = new FileInputStream(file)) {
while (input.available() >= 91 && -1 != input.read(name)) {
input.read(street);
input.read(city);
input.read(state);
input.read(zip);
contacts.add(new Contact(
new String(name, "UTF-8"),
new String(street, "UTF-8"),
new String(city, "UTF-8"),
new String(state, "UTF-8"),
new String(zip, "UTF-8")
));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveContacts() {
try (FileOutputStream out = new FileOutputStream(file)) {
for (Contact c : contacts) {
out.write(getFixedSizeByteArray(c.getFullName(), 32));
out.write(getFixedSizeByteArray(c.getStreet(), 32));
out.write(getFixedSizeByteArray(c.getCity(), 20));
out.write(getFixedSizeByteArray(c.getState(), 2));
out.write(getFixedSizeByteArray(c.getZip(), 5));
}
} catch (IOException e) {
e.printStackTrace();
}
}
private byte[] getFixedSizeByteArray(String string, int fixedSize) {
byte[] src = string.getBytes();
byte[] fixedArray = new byte[fixedSize];
System.arraycopy(src, 0, fixedArray, 0, Math.min(src.length, fixedSize));
return fixedArray;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.