Need help with this GUI java program. I have provided the source packages below but could not get to work. Can you help?
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).
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());
}
}
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
Expert Answer
please check the below code: invoice.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package business;
/**
*
* @author 123
*/
public class invoice extends javax.swing.JFrame {
/**
* Creates new form invoice
*/
public invoice() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings(“unchecked”)
// <editor-fold defaultstate=”collapsed” desc=”Generated Code”>
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setText(“Product Name”);
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 70, -1, -1));
jLabel2.setText(“Product Quantity(1 to 1000)”);
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 130, -1, -1));
jLabel3.setText(“Product Cost(10 to 10000)”);
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 190, -1, -1));
getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 260, -1, -1));
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 70, 190, 40));
getContentPane().add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 130, 190, 40));
getContentPane().add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 190, 190, 50));
getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 260, -1, -1));
getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 280, -1, -1));
getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 300, -1, -1));
getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 320, -1, -1));
getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 340, -1, -1));
jButton1.setText(“Calculate Total Cost”);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 370, 220, 60));
getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 10, -1, -1));
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String p_name = jTextField1.getText();
int p_quantity = Integer.parseInt(jTextField2.getText());
int p_cost = Integer.parseInt(jTextField3.getText());
int total_cost=0;
// the below conditional construct is to check whether the product quantity is between 1 and 1000
if(p_quantity<1 || p_quantity>1000)
{
jLabel10.setText(“please enter product quantity between 1 and 1000”);
}
// the below conditional construct will check whether the product cost is between 10 and 10000
else if(p_cost<10 || p_cost>10000)
{
jLabel10.setText(“please enter product cost between 10 and 10000”);
}
else
{
// this is the logic for total cost and printing.
total_cost = p_quantity * p_cost;
jLabel4.setText(“Total Cost”);
jLabel5.setText(“Invoice Information:”);
jLabel6.setText(“Product Name:” + p_name);
jLabel7.setText(“Product Quantity:” + p_quantity);
jLabel8.setText(“Product Cost: $” + p_cost);
jLabel9.setText(“total_cost: $” + total_cost);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate=”collapsed” desc=” Look and feel setting code (optional) “>
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (“Nimbus”.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(invoice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(invoice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(invoice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(invoice.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new invoice().setVisible(true);
}
});
}
// Variables declaration – do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
// End of variables declaration
}
___________________________________________________________________________________
output: