Question

In this practice program you are going to practice creating graphical user interface controls and placing them on a form. You are given a working NetBeans project shell to start that works with a given Invoice object that keeps track of a product name, quantity of the product to be ordered and the cost of each item. You will then create the necessary controls to extract the user input and display the results of the invoice.

If you have any questions or need help post a question in the Practice/Programming Help in the Introduction & Resources module.

Review the Project Shell

Download the Netbeans Project WK2_Practice_Invoice - Shell.zip, unzip the project and open it up in NetBeans.

Carefully review the structure of the program and the given classes. Make sure you understand the structure before you attempt to modify the program. You can run the program, but you will see a blank form until you complete the steps below.

Modify the program code

In the program code you will see several "TODO" comments (you can select "Window|Action Items" to see a list of the TODOs, clicking on an item will jump you to the place in the code).

You will create the GUI components and add the controls to the form for: (naming of the controls as shown is important!)

Product name label

Product name textfield (name: txtProductName)

Quantity label

Quantity textfield (name: txtQuantity)

Item cost label

Item cost textfield (name: txtCost)

JButton to calculate the cost (name: btnCalculate)

Add a CalculateHandler handler object to the btnCalculate addActionListener

Your final working program will look something like the following (note this is an example only, your form will look different).

Week 2 Practice Program?-Invoice Product Name Coffee Cup Product Quantity (1 to 1000) 100 Item cost (10 to 10000) 10 Invoice Information: Product Name: Coffee Cup Number of items: 100 Price Per Item: $10.00 Total cost: $1,000.00 Total cost Calculate Total Cost

It has three class files.

Invoice.java

package business;

import java.text.NumberFormat;
import java.util.Locale;

public class Invoice {
  
private String productName;
private int quantityPurchased;
private double pricePerItem;

public Invoice() {
setProductName("");;
setQuantityPurchased(1);
setPricePerItem(10);
}
public Invoice(String productName, int quantityPurchased, double pricePerItem) {
setProductName(productName);
setQuantityPurchased(quantityPurchased);
setPricePerItem(pricePerItem);
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
if(productName != null && !productName.trim().isEmpty()) {
this.productName = productName;
}
else {
this.productName = "Unknown product";
}
}
public int getQuantityPurchased() {
return quantityPurchased;
}
public void setQuantityPurchased(int quantityPurchased) {
if (quantityPurchased >= 1 && quantityPurchased <= 1000) {
this.quantityPurchased = quantityPurchased;
}
else if (quantityPurchased < 1) {
this.quantityPurchased = 1;
}
else {
this.quantityPurchased = 1000;
}
}
public double getPricePerItem() {
return pricePerItem;
}
public void setPricePerItem(double pricePerItem) {
if (pricePerItem >= 10 && pricePerItem <= 10000) {
this.pricePerItem = pricePerItem;
}
else if (pricePerItem < 10) {
this.pricePerItem = 10;
}
else {
this.pricePerItem = 10000;
}
}
public double getTotalCost() {
return pricePerItem * quantityPurchased;
}
@Override
public String toString() {
NumberFormat cf = NumberFormat.getCurrencyInstance(Locale.US);
StringBuilder str = new StringBuilder();
str.append("Invoice Information:");
str.append("\nProduct Name: ");
str.append(productName);
str.append("\nNumber of items: ");
str.append(quantityPurchased);
str.append("\nPrice Per Item: ");
str.append(cf.format(pricePerItem));
str.append("\nTotal cost: ");
str.append(cf.format(getTotalCost()));
return str.toString();
}
}

Invoice_GUI.java

package presentation;

import business.Invoice;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Invoice_GUI extends JFrame {
  
public static final int WINDOW_WIDTH = 450;
public static final int WINDOW_HEIGHT = 400;
  
private Invoice aInvoice;
  
private JButton btnCalculate;
private JButton btnClear;
private JButton btnExit;
  
private JTextField txtProductName;
private JTextField txtQuantity;
private JTextField txtCostPerItem;
private JTextArea txtTotalCost;
  
public Invoice_GUI() {
super();
createPanel();
setFrame();
}
  
private void createPanel() {
super.setLayout(new GridLayout(0, 2));
//TODO: create the GUI components and add them to the form for:
/*
1. Product name label
2. Product name textfield (name: txtProductName)
3. Quantity label
4. Quanitity textfield (name: txtQuantity)
5. Item cost label
6. Item cost textfield (name: txtCost)
7. JButton to calculate the cost (name: btnCalculate
8. Add a CalculateHandler handler object to the btnCalculate addActionListener
*/
}
private void setFrame() {
Dimension windowSize = new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT);

super.setTitle("Week 2 Practice Program--Invoice");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

super.setSize(windowSize);
super.setMinimumSize(windowSize);
super.setMaximumSize(windowSize);

super.setLocationRelativeTo(null);
super.setVisible(true);
}
private class CalculateHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
boolean valid;
if (aInvoice == null) {
//TODO: create a new invoice object
aInvoice = new Invoice();
}
aInvoice.setProductName(txtProductName.getText());

try {
int quanity = Integer.parseInt(txtQuantity.getText());
aInvoice.setQuantityPurchased(quanity);
valid = true;
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Quantity needs to be a number between 1 and 1000",
"Illegal Quanity value",
JOptionPane.ERROR_MESSAGE);
valid = false;
txtQuantity.setText("");
txtQuantity.requestFocus();
}
if (valid) {
try {
double cost = 0;
//TODO: write the state to extract the double value from the txtCost field
aInvoice.setPricePerItem(cost);
}
catch (NumberFormatException ex) {
valid = false;
JOptionPane.showMessageDialog(null, "Costs needs to be a number between 10 and 10000",
"Illegal Cost value",
JOptionPane.ERROR_MESSAGE);
valid = false;
txtCostPerItem.setText("");
txtCostPerItem.requestFocus();
}
}
if (valid) {
//TODO: using the toString method of the invoice object to set the output text
}
}
}

@Override
public String toString() {
return "Invoice_GUI{" + "aInvoice=" + aInvoice + ", btnCalculate=" + btnCalculate + ", btnClear=" + btnClear + ", btnExit=" + btnExit + ", txtProductName=" + txtProductName + ", txtQuantity=" + txtQuantity + ", txtCostPerItem=" + txtCostPerItem + ", txtTotalCost=" + txtTotalCost + '}';
}
  
}

Invoice_Main.java

package presentation;

import java.util.Scanner;

public class Invoice_Main {

  

public static void main(String[] args) {

new Invoice_GUI();

Scanner sc = new Scanner(System.in);

System.out.println("Enter the name of the Product");

invoice.setProductName(sc.nextLine());

System.out.println("Enter the Quantity Purchased");

invoice.setQuantityPurchased(sc.nextInt());

System.out.println("Enter the price of the item");

invoice.setPricePerItem(sc.nextDouble());

System.out.println("\nProduct Purchased : " + invoice.getProductName());

System.out.println("Total Cost : " + invoice.invoiceAmount());

}

}

  

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have completed the required program for you. Added all the labels, textfields, and registered the button click listener to find and set the cost appropriately. Thanks

// Invoice_GUI.java

import java.awt.Dimension;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import java.awt.GridLayout;

import java.awt.Insets;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

public class Invoice_GUI extends JFrame {

                public static final int WINDOW_WIDTH = 450;

                public static final int WINDOW_HEIGHT = 400;

                private Invoice aInvoice;

                private JButton btnCalculate;

                private JButton btnClear;

                private JButton btnExit;

                private JTextField txtProductName;

                private JTextField txtQuantity;

                private JTextField txtCost;

                private JTextArea txtTotalCost;

                public Invoice_GUI() {

                                super();

                                createPanel();

                                setFrame();

                }

                private void createPanel() {

                                super.setLayout(new GridLayout(0, 2));

                                // creating the GUI components and adding them to the form for:

                                /*

                                * 1. Product name label 2. Product name textfield (name:

                                * txtProductName) 3. Quantity label 4. Quanitity textfield (name:

                                * txtQuantity) 5. Item cost label 6. Item cost textfield (name:

                                * txtCost) 7. JButton to calculate the cost (name: btnCalculate 8. Add

                                * a CalculateHandler handler object to the btnCalculate

                                * addActionListener

                                */

                                add(new JLabel("Product Name"));

                                txtProductName = new JTextField();

                                add(txtProductName);

                                add(new JLabel("Product Quantity (1 to 1000)"));

                                txtQuantity = new JTextField();

                                add(txtQuantity);

                                add(new JLabel("Item cost (10 to 10000)"));

                                txtCost = new JTextField();

                                add(txtCost);

                                add(new JLabel("Total Cost"));

                                txtTotalCost = new JTextArea();

                                txtTotalCost.setEditable(false);

                                add(txtTotalCost);

                                btnCalculate = new JButton("Calculate total cost");

                                add(btnCalculate);

                                //adding button click handler

                                btnCalculate.addActionListener(new CalculateHandler());

                }

                private void setFrame() {

                                Dimension windowSize = new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT);

                                super.setTitle("Week 2 Practice Program--Invoice");

                                super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                                super.setSize(windowSize);

                                super.setMinimumSize(windowSize);

                                super.setMaximumSize(windowSize);

                                super.setLocationRelativeTo(null);

                                super.setVisible(true);

                }

                private class CalculateHandler implements ActionListener {

                                @Override

                                public void actionPerformed(ActionEvent ae) {

                                                boolean valid;

                                                if (aInvoice == null) {

                                                                //creating a new invoice object

                                                                aInvoice = new Invoice();

                                                }

                                                aInvoice.setProductName(txtProductName.getText());

                                                try {

                                                                int quanity = Integer.parseInt(txtQuantity.getText());

                                                                aInvoice.setQuantityPurchased(quanity);

                                                                valid = true;

                                                } catch (NumberFormatException ex) {

                                                                JOptionPane.showMessageDialog(null,

                                                                                                "Quantity needs to be a number between 1 and 1000",

                                                                                                "Illegal Quanity value", JOptionPane.ERROR_MESSAGE);

                                                                valid = false;

                                                                txtQuantity.setText("");

                                                                txtQuantity.requestFocus();

                                                }

                                                if (valid) {

                                                                try {

                                                                                double cost = 0;

                                                                                // extracting the double value from

                                                                                // the txtCost field

                                                                                cost = Double.parseDouble(txtCost.getText());

                                                                                aInvoice.setPricePerItem(cost);

                                                                } catch (NumberFormatException ex) {

                                                                                valid = false;

                                                                                JOptionPane.showMessageDialog(null,

                                                                                                                "Costs needs to be a number between 10 and 10000",

                                                                                                                "Illegal Cost value", JOptionPane.ERROR_MESSAGE);

                                                                                valid = false;

                                                                                txtCost.setText("");

                                                                                txtCost.requestFocus();

                                                                }

                                                }

                                                if (valid) {

                                                                // using the toString method of the invoice object to set

                                                                // the output text

                                                                txtTotalCost.setText(aInvoice.toString());

                                                                pack();

                                                }

                                }

                }

                @Override

                public String toString() {

                                return "Invoice_GUI{" + "aInvoice=" + aInvoice + ", btnCalculate="

                                                                + btnCalculate + ", btnClear=" + btnClear + ", btnExit="

                                                                + btnExit + ", txtProductName=" + txtProductName

                                                                + ", txtQuantity=" + txtQuantity + ", txtCostPerItem="

                                                                + txtCost + ", txtTotalCost=" + txtTotalCost + '}';

                }

}

// Invoice.java

import java.text.NumberFormat;

import java.util.Locale;

public class Invoice {

                private String productName;

                private int quantityPurchased;

                private double pricePerItem;

                public Invoice() {

                                setProductName("");

                                setQuantityPurchased(1);

                                setPricePerItem(10);

                }

                public Invoice(String productName, int quantityPurchased,

                                                double pricePerItem) {

                                setProductName(productName);

                                setQuantityPurchased(quantityPurchased);

                                setPricePerItem(pricePerItem);

                }

                public String getProductName() {

                                return productName;

                }

                public void setProductName(String productName) {

                                if (productName != null && !productName.trim().isEmpty()) {

                                                this.productName = productName;

                                } else {

                                                this.productName = "Unknown product";

                                }

                }

                public int getQuantityPurchased() {

                                return quantityPurchased;

                }

                public void setQuantityPurchased(int quantityPurchased) {

                                if (quantityPurchased >= 1 && quantityPurchased <= 1000) {

                                                this.quantityPurchased = quantityPurchased;

                                } else if (quantityPurchased < 1) {

                                                this.quantityPurchased = 1;

                                } else {

                                                this.quantityPurchased = 1000;

                                }

                }

                public double getPricePerItem() {

                                return pricePerItem;

                }

                public void setPricePerItem(double pricePerItem) {

                                if (pricePerItem >= 10 && pricePerItem <= 10000) {

                                                this.pricePerItem = pricePerItem;

                                } else if (pricePerItem < 10) {

                                                this.pricePerItem = 10;

                                } else {

                                                this.pricePerItem = 10000;

                                }

                }

                public double getTotalCost() {

                                return pricePerItem * quantityPurchased;

                }

                @Override

                public String toString() {

                                NumberFormat cf = NumberFormat.getCurrencyInstance(Locale.US);

                                StringBuilder str = new StringBuilder();

                                str.append("Invoice Information:");

                                str.append("\nProduct Name: ");

                                str.append(productName);

                                str.append("\nNumber of items: ");

                                str.append(quantityPurchased);

                                str.append("\nPrice Per Item: ");

                                str.append(cf.format(pricePerItem));

                                str.append("\nTotal cost: ");

                                str.append(cf.format(getTotalCost()));

                                return str.toString();

                }

}

// Invoice_Main.java

import java.util.Scanner;

public class Invoice_Main {

                public static void main(String[] args) {

                                new Invoice_GUI();

                                /*

                                * The below codes are unnecessary for this program, Scanner sc = new

                                * Scanner(System.in);

                                *

                                * System.out.println("Enter the name of the Product");

                                *

                                * invoice.setProductName(sc.nextLine());

                                *

                                * System.out.println("Enter the Quantity Purchased");

                                *

                                * invoice.setQuantityPurchased(sc.nextInt());

                                *

                                * System.out.println("Enter the price of the item");

                                *

                                * invoice.setPricePerItem(sc.nextDouble());

                                *

                                * System.out.println("\nProduct Purchased : " +

                                * invoice.getProductName());

                                *

                                * System.out.println("Total Cost : " + invoice.invoiceAmount());

                                */

                }

}

/*OUTPUT*/


Week 2 Practice Program--Invoice Product Name Mobile Phone 3 Item cost (10 to 10000) 299 Invoice Information: Product Name: M

Add a comment
Know the answer?
Add Answer to:
In this practice program you are going to practice creating graphical user interface controls and placing...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please design a Java GUI application with two JTextField for user to enter the first name...

    Please design a Java GUI application with two JTextField for user to enter the first name and last name. Add two JButtons with action events so when user click on one button to generate a full name message from the user input and put it in a third JTextField which is not editable; and click on the other button to clear all three JTextField boxes. Please run the attached nameFrame.class file (Note: because there is an actionhandler inner class in...

  • Lab Assignment : In this lab, you are going to implement QueueADT interface that defines a...

    Lab Assignment : In this lab, you are going to implement QueueADT interface that defines a queue. Then you are going to use the queue to store animals. 1. Write a LinkedQueue class that implements the QueueADT.java interface using links. 2. Textbook implementation uses a count variable to keep track of the elements in the queue. Don't use variable count in your implementation (points will be deducted if you use instance variable count). You may use a local integer variable...

  • I tried to add exception handling to my program so that when the user puts in...

    I tried to add exception handling to my program so that when the user puts in an amount of change that is not the integer data type, the code will catch it and tell them to try again, but my try/catch isnt working. I'm not sure how to fix this problem. JAVA code pls package Chapter9; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GUIlab extends JFrame implements ActionListener {    private static final int WIDTH = 300;    private...

  • Can someone modify my code so that I do not get this error: Exception in thread...

    Can someone modify my code so that I do not get this error: Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl(Container.java:1043) at java.awt.Container.add(Container.java:363) at RatePanel.<init>(RatePanel.java:64) at CurrencyConverter.main(CurrencyConverter.java:16) This code should get the amount of money in US dollars from user and then let them select which currency they are trying to convert to and then in the textfield print the amount //********************************************************************* //File name: RatePanel.java //Name: Brittany Hines //Purpose: Panel for a program that convers different currencyNamerencies to use dollars //*********************************************************************...

  • Swing File Adder: Build a GUI that contains an input file, text box and Infile button....

    Swing File Adder: Build a GUI that contains an input file, text box and Infile button. It also must contain and output file, text box and Outfile button. Must also have a process button must read the infile and write to the outfile if not already written that is already selected and clear button. It must pull up a JFile chooser that allows us to brows to the file and places the full path name same with the output file.  Program...

  • please help me debug this Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart...

    please help me debug this Create a Future Value Calculator that displays error messages in labels.GUISpecificationsStart with the JavaFX version of the Future Value application presented in chapter 17. Create error message labels for each text field that accepts user input. Use the Validation class from chapter 17 to validate user input.Format the application so that the controls don’t change position when error messages are displayed. package murach.business; public class Calculation {        public static final int MONTHS_IN_YEAR =...

  • Write a program in Java that prompts a user for Name and id number. and then...

    Write a program in Java that prompts a user for Name and id number. and then the program outputs students GPA MAIN import java.util.StringTokenizer; import javax.swing.JOptionPane; public class Main {    public static void main(String[] args) {                       String thedata = JOptionPane.showInputDialog(null, "Please type in Student Name. ", "Student OOP Program", JOptionPane.INFORMATION_MESSAGE);        String name = thedata;        Student pupil = new Student(name);                   //add code here       ...

  • This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).

    Ch 7 Program: Online shopping cart (continued) (Java)This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class per the following specifications:Private fieldsstring itemDescription - Initialized in default constructor to "none"Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt)Public member methodssetDescription() mutator & getDescription() accessor (2 pts)printItemCost() - Outputs the item name followed by the quantity, price, and subtotalprintItemDescription() - Outputs the...

  • Below, you can find the description of your labwork for today. You can also find the...

    Below, you can find the description of your labwork for today. You can also find the expected output of this code in the Application Walkthrough section. You are going to improve your existing Money & Stock Trading Platform on previous week’s labwork by incorporating Collections. In previous labworks, you have used arrays for holding Customer and Item objects. For this labwork you need to use ArrayList for holding these objects. So, rather than defining Customer[] array, you need to define...

  • I have been messing around with java lately and I have made this calculator. Is there...

    I have been messing around with java lately and I have made this calculator. Is there any way that I would be able to get a different sound to play on each different button 1 - 9 like a nokia phone? Thank you. *SOURCE CODE* import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Calculator extends JFrame { private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20); private JTextField textfield; private boolean number = true; private String equalOp = "="; private...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT