class not retrieving information from another class - java

Grocery_shop
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
/**
Grocery shop class
*/
public class Grocery_shop extends JFrame
{
private quantitypanel qty; // A panel for quantity
private Grocery_items items; // A panel for routine charge checkboxes
private JPanel buttonPanel; // A panel for the buttons
private JButton calcButton; // Calculates everything
private JButton exitButton; // Exits the application
private invoiceClass invoice;
/**
Constructor
*/
public Grocery_shop()
{
// Display a title.
setTitle("Victor's Grocery Shop");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a NonRoutinePanel object.
qty = new quantitypanel();
// qty.setBackground(Color.white);
// Create a RoutinePanel object.
items = new Grocery_items( qty );
// Build the panel that contains the buttons.
buildButtonPanel();
// Add the panels to the content pane.
add(items, BorderLayout.WEST);
add(qty, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
// Pack and display the window.
pack();
setVisible(true);
}
/**
The buildButtonPanel method creates a panel containing
buttons.
*/
private void buildButtonPanel()
{
// Create a button to calculate the charges.
calcButton = new JButton("Add Charges");
// Add an action listener to the button.
calcButton.addActionListener(new CalcButtonListener());
// Create a button to exit the application.
exitButton = new JButton("Exit");
// Add an action listener to the button.
exitButton.addActionListener(new ExitButtonListener());
// Put the buttons in their own panel.
buttonPanel = new JPanel();
buttonPanel.add(calcButton);
buttonPanel.add(exitButton);
}
/**
CalcButtonListener is an action listener class for the
calcButton component.
*/
private class CalcButtonListener implements ActionListener
{
/**
actionPerformed method
#param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e)
{
double totalCharges; // Total charges
// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Calculate the total charges
totalCharges = items.getCharges();
//+ nonRoutine.getCharges();
// Display the message.
JOptionPane.showMessageDialog(null, "Total Charges: $" +
dollar.format(totalCharges));
invoice = new invoiceClass();
invoice.getClass();
}
} // End of inner class
/**
ExitButtonListener is an action listener class for the
exitButton component.
*/
private class ExitButtonListener implements ActionListener
{
/**
actionPerformed method
#param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
} // End of inner class
/**
The main method creates an instance of the JoesAutomotive
class, causing it to display its window.
*/
public static void main(String[] args)
{
Grocery_shop grocery = new Grocery_shop();
}
}
Grocery_items
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
/**
RoutinePanel class
*/
public class Grocery_items extends JPanel
{
// Named constants for charges
private final double Baked_Beans = 0.35;
private final double Cornflakes = 1.75;
private final double Sugar = 0.75;
private final double Tea_Bags = 1.15;
private final double Instant_Coffee = 2.50;
private final double Bread = 1.25;
private final double Sausage = 1.30;
private final double Eggs = 0.75;
private final double Milk = 0.65;
private final double Potatoes = 2.00;
private quantitypanel qty; // A panel for quantity
private JCheckBox baked_beans_box; // Check box for baked_beans
private JCheckBox CornflakesBox; // Check box for cornflakes
private JCheckBox SugarBox; // Check box for sugar box
private JCheckBox Tea_Bags_Box; // Check box for tea bag
private JCheckBox Instant_Coffee_Box; // Check box for Instant_Coffee_Box
private JCheckBox Bread_Box; // Check box for bread box
private JCheckBox SausageBox; // Check box for sausage box
private JCheckBox eggbox; // Check box for egg box
private JCheckBox milkbox; // Check box for milk
private JCheckBox potatoesbox; // Check box for potatoes
// private JTextField baked_beans_JT;
/**
Constructor
*/
public Grocery_items(quantitypanel qty)
{
this.qty = qty;
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Create the check boxes.
baked_beans_box = new JCheckBox("Baked_Beans ($" +
dollar.format(Baked_Beans) + ")");
CornflakesBox = new JCheckBox("Cornflakes ($" +
dollar.format(Cornflakes) + ")");
SugarBox = new JCheckBox("Sugar ($" +
dollar.format(Sugar) + ")");
Tea_Bags_Box = new JCheckBox("Tea Bags ($" +
dollar.format(Tea_Bags) + ")");
Instant_Coffee_Box = new JCheckBox("Instant Coffee_Box ($" +
dollar.format(Instant_Coffee) + ")");
Bread_Box = new JCheckBox("Bread Box ($" +
dollar.format(Bread) + ")");
SausageBox = new JCheckBox("Suasages ($" +
dollar.format(Sausage) + ")");
eggbox = new JCheckBox("Eggs ($" +
dollar.format(Eggs) + ")");
milkbox = new JCheckBox("Milk ($" +
dollar.format(Milk) + ")");
potatoesbox = new JCheckBox("Potatoes ($" +
dollar.format(Potatoes) + ")");
// Create a GridLayout manager.
setLayout(new GridLayout(10, 1));
// Create a border.
setBorder(BorderFactory.createTitledBorder("Grocery Items"));
// Add the check boxes to this panel.
add(baked_beans_box);
add(CornflakesBox);
add(SugarBox);
add(Tea_Bags_Box);
add(Instant_Coffee_Box);
add(Bread_Box);
add(SausageBox);
add(eggbox);
add(milkbox);
add(potatoesbox);
}
/**
The getCharges method calculates the routine charges.
#return The amount of routine charges.
*/
public double getCharges()
{
double charges = 0;
if (baked_beans_box.isSelected())
charges += Baked_Beans * qty.getBeanqty();
if (CornflakesBox.isSelected())
charges += Cornflakes;
if (SugarBox.isSelected())
charges += Sugar;
if (Tea_Bags_Box.isSelected())
charges += Tea_Bags;
if (Instant_Coffee_Box.isSelected())
charges += Instant_Coffee;
if (Bread_Box.isSelected())
charges += Bread;
if (SausageBox.isSelected())
charges += Sausage;
if (eggbox.isSelected())
charges += Eggs;
if (milkbox.isSelected())
charges += Milk;
if (potatoesbox.isSelected())
charges += Potatoes;
return charges;
}
}
quantitypanel
//import java.awt.LayoutManager;
import java.awt.GridLayout;
//import javax.swing.JCheckBox;
//import javax.swing.JLabel;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class quantitypanel extends JPanel {
private JTextField baked_beans_JT; // JTextField box for baked_beans
private JTextField Cornflakes_JT; // JTextField box for cornflakes
private JTextField Sugar_JT; // JTextField box for sugar box
private JTextField Tea_Bags_JT; // JTextField box for tea bag
private JTextField Instant_Coffee_JT; // JTextField box for Instant_Coffee_Box
private JTextField Bread_JT; // JTextField box for bread box
private JTextField Sausage_JT; // JTextField box for sausage box
private JTextField egg_JT; // JTextField box for egg box
private JTextField milk_JT; // JTextField box for milk
private JTextField potatoes_JT; // JTextField box for potatoes
public quantitypanel()
{
//create JTextField.
baked_beans_JT = new JTextField(5);
Cornflakes_JT = new JTextField(5);
Sugar_JT = new JTextField(5);
Tea_Bags_JT = new JTextField(5);
Instant_Coffee_JT = new JTextField(5);
Bread_JT = new JTextField(5);
Sausage_JT = new JTextField(5);
egg_JT = new JTextField(5);
milk_JT = new JTextField(5);
potatoes_JT = new JTextField(5);
//initialize text field to 0
baked_beans_JT.setText("0");
Cornflakes_JT.setText("0");
Sugar_JT.setText("0");
Tea_Bags_JT.setText("0");
Instant_Coffee_JT.setText("0");
Bread_JT.setText("0");
Sausage_JT.setText("0");
egg_JT.setText("0");
milk_JT.setText("0");
potatoes_JT.setText("0");
//set Layout manager
setLayout(new GridLayout(10, 1));
//create border and panel title
setBorder(BorderFactory.createTitledBorder("Amount"));
//add text fields to the panel.
add(baked_beans_JT);
add(Cornflakes_JT);
add(Sugar_JT);
add(Tea_Bags_JT);
add(Instant_Coffee_JT);
add(Bread_JT);
add(Sausage_JT);
add(egg_JT);
add(milk_JT);
add(potatoes_JT);
}
public double getBeanqty()
{
try
{
return Double.parseDouble(baked_beans_JT.getText());
}
catch(NumberFormatException ev){
JOptionPane.showMessageDialog(null, "invalid");
}
return 0;
}
}
invoiceClass
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class invoiceClass {
private Grocery_items items;
private quantitypanel qty; // A panel for quantity
{
double total; // Total charges
DecimalFormat dollar = new DecimalFormat("#,##0.00");
qty = new quantitypanel();
items = new Grocery_items(qty);
// Calculate the total charges
double payment = 0.0;
String input;
input = JOptionPane.showInputDialog(null, "enter a your payment");
payment = Double.parseDouble(input);
total = payment - items.getCharges();
JOptionPane.showMessageDialog(null, "your change is: " + total);
}
}
Please with the code above, i'm trying to make a receipt for the program.
I want in this code total = payment - items.getCharges(); for the system to get the total charges and subtract it from the number the user inputs. In this case the system is only recognising the payment.
Please help..
thanks

The reason that items.getCharges() returns 0 is that a new invoiceClass instance is created every time a CalcButtonListener Action occurs. This creates a new Grocery_items instance.
This, in turn, creates new GUI elements including checkboxes. These checkboxes are not the ones visible in the application as they have not been added. Now when you go to call getCharges, the selection state of the JCheckBoxes on the newly created Grocery_items will be false (default state of JCheckBox) so no charges will be added
public double getCharges() {
double charges = 0;
if (baked_beans_box.isSelected()) // now false!
charges += Baked_Beans * qty.getBeanqty();
if (...)
The solution, therefore, is not to create Grocery_items in quantitypanel but to use the original instance.
Aside: Use Java naming conventions have classes that start with uppercase such as QuantityPanel. Underscores are typically not used, e.g. GroceryItems

Related

Double cannot be converted to JTextField

On lines, 139 - 146 the error "Double cannot be converted to JTextField" comes up. I understand that I need to change the name of the variable but I am unsure where to change it. I've attempted to change the names under CalcButtonListener but it created more errors. Thank you for your time and help!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TravelExpenses extends JFrame
{
private JPanel panel;
private JPanel buttonPanel;
private JTextField numDays;
private JTextField airfare;
private JTextField carRent;
private JTextField miles;
private JTextField parking;
private JTextField taxi;
private JTextField reg;
private JTextField lodge;
private JButton calcButton;
private JButton resetButton;
public TravelExpenses()
{
setTitle("Travel Expenses");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
buildButtonPanel();
add(panel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
private void buildPanel()
{
//labels for text fields
JLabel numDaysLabel = new JLabel("Number of days of the trip:");
JLabel airfareLabel = new JLabel("Amount of airfare:");
JLabel carRentLabel = new JLabel("Amount of car rental:");
JLabel milesLabel = new JLabel("Miles driven(if a private vehicle was used):");
JLabel parkingLabel = new JLabel("Parking fees:");
JLabel taxiLabel = new JLabel("Taxi fees:");
JLabel regLabel = new JLabel("Conference registaration:");
JLabel lodgeLabel = new JLabel("Lodging charges per night:");
//text fields
numDays = new JTextField(10);
airfare = new JTextField(10);
carRent = new JTextField(10);
miles = new JTextField(10);
parking = new JTextField(10);
taxi = new JTextField(10);
reg = new JTextField(10);
lodge = new JTextField(10);
//new panel
panel = new JPanel();
//layout manager
panel.setLayout(new GridLayout( 10,8));
//add labels and text fields
panel.add(numDaysLabel);
panel.add(numDays);
panel.add(airfareLabel);
panel.add(airfare);
panel.add(carRentLabel);
panel.add(carRent);
panel.add(milesLabel);
panel.add(miles);
panel.add(parkingLabel);
panel.add(parking);
panel.add(taxiLabel);
panel.add(taxi);
panel.add(regLabel);
panel.add(reg);
panel.add(lodgeLabel);
panel.add(lodge);
//put border around panel
panel.setBorder(BorderFactory.createEmptyBorder(10,10, 1, 10));
}
//method creates button panel
private void buildButtonPanel()
{
//create button for calc
calcButton = new CButton("Calculate");
calcButton.addActionListener(new CalcButtonListener());
resetButton = new JButton("Reset");
resetButton.addActionListener(new ResetButtonListener());
buttonPanel = new JPanel();
buttonPanel.add(resetButton);
buttonPanel.add(calcButton);
}
//listener for calc button
private class CalcButtonListener implements ActionListener
{
double numDays;
double airfare;
double carRent;
double miles;
double parking;
double taxi;
double reg;
double lodge;
public void actionPerformed(Action e)
{
double total;
String msg;
//get data
getData();
//total
total = determineTotal();
msg = String.format("Total cost: $%,.2f\n", total);
JOptionPane.showMessageDialog(null, msg);
}
}
**Below is the chunk I am having issues with**
private void getData()
{
numDays = Double.parseDouble(numDays.getText());
airfare = Double.parseDouble(airfare.getText());
carRent = Double.parseDouble(carRent.getText());
miles = Double.parseDouble(miles.getText());
parking = Double.parseDouble(parking.getText());
taxi = Double.parseDouble(taxi.getText());
reg = Double.parseDouble(reg.getText());
lodge = Double.parseDouble(lodge.getText());
}
On lines, 139 - 146 you are accessing members of TravelExpenses class rather than CalcButtonListener class.
Put getData() and determineTotal() method in CalcButtonListener class and use scope specifiers of particular member like for JtextField use:TravelExpenses.this.numDays as like for all JtextField.
Use below code for CalcButtonListener:
private class CalcButtonListener implements ActionListener
{
double numDays;
double airfare;
double carRent;
double miles;
double parking;
double taxi;
double reg;
double lodge;
public void actionPerformed(Action e)
{
double total;
String msg;
//get data
getData();
//total
total = determineTotal();
msg = String.format("Total cost: $%,.2f\n", total);
JOptionPane.showMessageDialog(null, msg);
}
private void getData()
{
numDays = Double.parseDouble(TravelExpenses.this.numDays.getText());
airfare = Double.parseDouble(TravelExpenses.this.airfare.getText());
carRent = Double.parseDouble(TravelExpenses.this.carRent.getText());
miles = Double.parseDouble(TravelExpenses.this.miles.getText());
parking = Double.parseDouble(TravelExpenses.this.parking.getText());
taxi = Double.parseDouble(TravelExpenses.this.taxi.getText());
reg = Double.parseDouble(TravelExpenses.this.reg.getText());
lodge = Double.parseDouble(TravelExpenses.this.lodge.getText());
}
private double determineTotal()
{
double total = numDays * airfare * carRent * miles * parking * taxi * reg * lodge;
return total;
}
}
Here you can find complete code.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TravelExpenses extends JFrame {
private JPanel panel;
private JPanel buttonPanel;
private JTextField numDays;
private JTextField airfare;
private JTextField carRent;
private JTextField miles;
private JTextField parking;
private JTextField taxi;
private JTextField reg;
private JTextField lodge;
private JButton calcButton;
private JButton resetButton;
public TravelExpenses() {
setTitle("Travel Expenses");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
buildButtonPanel();
add(panel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
private void buildPanel() {
// labels for text fields
JLabel numDaysLabel = new JLabel("Number of days of the trip:");
JLabel airfareLabel = new JLabel("Amount of airfare:");
JLabel carRentLabel = new JLabel("Amount of car rental:");
JLabel milesLabel = new JLabel("Miles driven(if a private vehicle was used):");
JLabel parkingLabel = new JLabel("Parking fees:");
JLabel taxiLabel = new JLabel("Taxi fees:");
JLabel regLabel = new JLabel("Conference registaration:");
JLabel lodgeLabel = new JLabel("Lodging charges per night:");
// text fields
numDays = new JTextField(10);
airfare = new JTextField(10);
carRent = new JTextField(10);
miles = new JTextField(10);
parking = new JTextField(10);
taxi = new JTextField(10);
reg = new JTextField(10);
lodge = new JTextField(10);
// new panel
panel = new JPanel();
// layout manager
panel.setLayout(new GridLayout(10, 8));
// add labels and text fields
panel.add(numDaysLabel);
panel.add(numDays);
panel.add(airfareLabel);
panel.add(airfare);
panel.add(carRentLabel);
panel.add(carRent);
panel.add(milesLabel);
panel.add(miles);
panel.add(parkingLabel);
panel.add(parking);
panel.add(taxiLabel);
panel.add(taxi);
panel.add(regLabel);
panel.add(reg);
panel.add(lodgeLabel);
panel.add(lodge);
// put border around panel
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 1, 10));
}
//method creates button panel
private void buildButtonPanel() {
// create button for calc
calcButton = new CButton("Calculate");
calcButton.addActionListener(new CalcButtonListener());
resetButton = new JButton("Reset");
resetButton.addActionListener(new ResetButtonListener());
buttonPanel = new JPanel();
buttonPanel.add(resetButton);
buttonPanel.add(calcButton);
}
//listener for calc button
private class CalcButtonListener implements ActionListener {
double numDays;
double airfare;
double carRent;
double miles;
double parking;
double taxi;
double reg;
double lodge;
public void actionPerformed(ActionEvent e) {
double total;
String msg;
// get data
getData();
// total
total = determineTotal();
msg = String.format("Total cost: $%,.2f\n", total);
JOptionPane.showMessageDialog(null, msg);
}
private void getData() {
numDays = Double.parseDouble(TravelExpenses.this.numDays.getText());
airfare = Double.parseDouble(TravelExpenses.this.airfare.getText());
carRent = Double.parseDouble(TravelExpenses.this.carRent.getText());
miles = Double.parseDouble(TravelExpenses.this.miles.getText());
parking = Double.parseDouble(TravelExpenses.this.parking.getText());
taxi = Double.parseDouble(TravelExpenses.this.taxi.getText());
reg = Double.parseDouble(TravelExpenses.this.reg.getText());
lodge = Double.parseDouble(TravelExpenses.this.lodge.getText());
}
private double determineTotal() {
double total = numDays * airfare * carRent * miles * parking * taxi * reg * lodge;
return total;
}
}
private class ResetButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// reset text fields
numDays.setText("0");
airfare.setText("0");
carRent.setText("0");
miles.setText("0");
parking.setText("0");
taxi.setText("0");
reg.setText("0");
lodge.setText("0");
}
}
public static void main(String[] args) {
TravelExpenses gc = new TravelExpenses();
}
}

Travel expenses GUI "Calculate reimbursement" button not responding

I can get the input box to appear, and can enter all of my data. The reset button works, but I cannot figure out why the calculate button refuses to show the output reimbursement.
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class TravelExpenses extends JFrame{
//info for labels
private JLabel daysOnTrip;
private JLabel carRental;
private JLabel airfair;
private JLabel parkingFees;
private JLabel taxiFees;
private JLabel milesDriven;
private JLabel conReg;
private JLabel lodgingNightCharges;
//reference panel obs
private JPanel travelInfo;
private JPanel buttonP;
//info from fields of texts
private JTextField daysOnTripText;
private JTextField carRentalText;
private JTextField airfairText;
private JTextField parkingFeesText;
private JTextField taxiFeesText;
private JTextField milesDrivenText;
private JTextField conRegText;
private JTextField lodgingNightChargesText;
//buttons that will be used to function
private JButton calculate; //will be used to calculate informaiton that the user enters when clicked
private JButton reset; // will be used to reset the fields as needed when clicked
//constants as specified
private double mealsCost = 37.00; //per day for meals
private double parkingFeesAmount = 10.00; // up to 10 per day
private double taxiFeesAmount = 20.00; // up to 20 per day
private double lodgingChargesAmount = 95.00; // up to 95 a day
private double mileAmount = 0.27; //per mile driven
/**
* Constructor
* #param args
*/
public TravelExpenses(){
//JFrame title called
super("Travel Expenses");
//center of desktop placement
setLocationRelativeTo(null);
//Close button will do this..
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//border layout mgr cp
setLayout(new BorderLayout());
//TravelInfo&Buttons
buildTravelInfoPanel();
buildButton();
// get panels to frame content
add(travelInfo, BorderLayout.CENTER);
add(buttonP, BorderLayout.SOUTH);
//window content display
pack();
setVisible(true);
}
private void buildTravelInfoPanel(){
//field labels made
daysOnTrip = new JLabel("Number of days for trip.");
airfair = new JLabel("Airfair Amount: ");
carRental = new JLabel ("Car Rental Cost Amount: ");
milesDriven = new JLabel ("Mile Driven: ");
parkingFees = new JLabel ("Parking Fees: ");
taxiFees = new JLabel ("Taxi Fees: ");
conReg = new JLabel ("Conference Registration Cost: ");
lodgingNightCharges = new JLabel ("Lodging Charges per Night: ");
//text boxes for input from user
daysOnTripText = new JTextField(3);
carRentalText = new JTextField(8);
airfairText = new JTextField(8);
parkingFeesText = new JTextField(6);
taxiFeesText = new JTextField(6);
milesDrivenText = new JTextField(4);
conRegText = new JTextField(8);
lodgingNightChargesText = new JTextField(6);
//panel for labels/text
travelInfo = new JPanel();
//Grid for 10 r and 2 c
travelInfo.setLayout(new GridLayout(10,2));
//labels and text for panel made
travelInfo.add(daysOnTrip);
travelInfo.add(daysOnTripText);
travelInfo.add(airfair);
travelInfo.add(airfairText);
travelInfo.add(carRental);
travelInfo.add(carRentalText);
travelInfo.add(milesDriven);
travelInfo.add(milesDrivenText);
travelInfo.add(parkingFees);
travelInfo.add(parkingFeesText);
travelInfo.add(taxiFees);
travelInfo.add(taxiFeesText);
travelInfo.add(conReg);
travelInfo.add(conRegText);
travelInfo.add(lodgingNightCharges);
travelInfo.add(lodgingNightChargesText);
}
/**
* buildButton is method that adds reset and calc buttons to main panel
* #param args
*/
private void buildButton(){
//caclulation button
calculate = new JButton("Calculate Reimbursment");
//event listiner for calculation
calculate.addActionListener(new CalculateListener());
//reset button
reset = new JButton("Reset");
//event listiner for reset
reset.addActionListener(new ResetListener());
//button panels
buttonP = new JPanel();
//buttons
buttonP.add(reset, BorderLayout.WEST);
buttonP.add(calculate, BorderLayout.CENTER);
}
/**
* CalculateListener will do event for calculate button
* #param args
*/
private class CalculateListener implements ActionListener{
//variables
String input;
int days;
double air;
double miles;
double carRental;
double conReg;
double lodging;
double parking;
double meals;
double taxi;
public void actionPerformed(ActionEvent e){
//variables
double actualExpenses;
double milesExpenses;
double allowed;
double exAirfair;
double exCarRen;
double exParking;
double exTaxi;
double exLodge;
double overTotal;
double savings;
double reimb;
//dec format implement
DecimalFormat money = new DecimalFormat("$#,###.00");
}
//get info from text fields
private void getInfo(){
days = Integer.parseInt(daysOnTripText.getText());
air = Double.parseDouble(airfairText.getText());
carRental = Double.parseDouble(carRentalText.getText());
miles = Double.parseDouble(milesDrivenText.getText());
parking = Double.parseDouble(parkingFeesText.getText());
taxi = Double.parseDouble(parkingFeesText.getText());
conReg = Double.parseDouble(conRegText.getText());
lodging = Double.parseDouble(lodgingNightChargesText.getText());
}
//figure out expenses
private void calcActualExpenses(double actualExpenses, double milesExpenses){
actualExpenses = air + carRental + parking + taxi + conReg + lodging;
milesExpenses = miles * mileAmount;
actualExpenses = actualExpenses + milesExpenses;
//display total
JOptionPane.showMessageDialog(null, "Total expenses: " + "\n"+
"Allowables expenses: " + "\n" +
"\n" + "Amount to be paid back: ");
}
}
//this handles reset button
private class ResetListener implements ActionListener{
public void actionPerformed(ActionEvent e){
daysOnTripText.setText("");
airfairText.setText("");
carRentalText.setText("");
milesDrivenText.setText("");
parkingFeesText.setText("");
taxiFeesText.setText("");
conRegText.setText("");
lodgingNightChargesText.setText("");
}
}
public static void main(String[] args) {
new TravelExpenses();
}
}
I can get the input box to appear, and can enter all of my data. The reset button works, but I cannot figure out why the calculate button refuses to show the output reimbursement.

Java: Action Handler

I am working on a problem for school and I am having an issue with the CalculateButtonHandler. I am also using an ExitButtonHandler but that is not giving me any issues. I have tried re-reading my textbook and have searched the web. After racking my brain over this issue I can't figure out why this won't work. This is my first GUI attempt and I am sure I will have to mess with the program to get it the way I want. I only want to know how to fix this CalculateButtonHandler issues as I can work on the rest if need be. Below is the code for the project.
Issues:
Lines 38, 76 and 77: CalculateButtonHandler cannot be resolved to a type.
What does this mean and how can I go about fixing it?
//This program calculates the weighted average of four test scores.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.math.*;
public class SNHU6_4 extends JFrame
{
private static final int WIDTH = 400;
private static final int LENGTH = 300;
private JLabel testscore1L;
private JLabel weight1L;
private JLabel testscore2L;
private JLabel weight2L;
private JLabel testscore3L;
private JLabel weight3L;
private JLabel testscore4L;
private JLabel weight4L;
private JLabel scoreL;
private JTextField testscore1TF;
private JTextField weight1TF;
private JTextField testscore2TF;
private JTextField weight2TF;
private JTextField testscore3TF;
private JTextField weight3TF;
private JTextField testscore4TF;
private JTextField weight4TF;
private JTextField scoreTF;
private JButton calculateB;
private JButton exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public SNHU6_4()
{
//Creating the labels
testscore1L = new JLabel ("Enter first test score: ", SwingConstants.RIGHT);
testscore2L = new JLabel ("Enter second test score: ", SwingConstants.RIGHT);
testscore3L = new JLabel ("Enter third test score: ", SwingConstants.RIGHT);
testscore4L = new JLabel ("Enter fourth test score: ", SwingConstants.RIGHT);
weight1L = new JLabel ("Enter first test score weight : ", SwingConstants.RIGHT);
weight2L = new JLabel ("Enter second test score weight :", SwingConstants.RIGHT);
weight3L = new JLabel ("Enter third test score weight :", SwingConstants.RIGHT);
weight4L = new JLabel ("Enter fourth test score weight :", SwingConstants.RIGHT);
scoreL = new JLabel ("Final score: ", SwingConstants.RIGHT);
//Creating the text fields
testscore1TF = new JTextField ("0",5);
testscore1TF.setHorizontalAlignment(JTextField.CENTER);
testscore2TF = new JTextField ("0",5);
testscore1TF.setHorizontalAlignment(JTextField.CENTER);
testscore3TF = new JTextField ("0",5);
testscore3TF.setHorizontalAlignment(JTextField.CENTER);
testscore4TF = new JTextField ("0",5);
testscore4TF.setHorizontalAlignment(JTextField.CENTER);
weight1TF = new JTextField ("0",5);
weight1TF.setHorizontalAlignment(JTextField.CENTER);
weight2TF = new JTextField ("0",5);
weight2TF.setHorizontalAlignment(JTextField.CENTER);
weight3TF = new JTextField ("0",5);
weight3TF.setHorizontalAlignment(JTextField.CENTER);
weight4TF = new JTextField ("0",5);
weight4TF.setHorizontalAlignment(JTextField.CENTER);
scoreTF = new JTextField ("0",5);
scoreTF.setHorizontalAlignment(JTextField.CENTER);
//Creating the calculate button
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
//Creating the exit button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
//Creating the window title
setTitle ("Weighted Average of Test Scores");
//Get the container
Container pane = getContentPane();
//Set the layout
pane.setLayout(new GridLayout(5, 4));
//Placing components in the pane
pane.add(testscore1L);
pane.add(testscore1TF);
pane.add(testscore2L);
pane.add(testscore2TF);
pane.add(testscore3L);
pane.add(testscore3TF);
pane.add(testscore4L);
pane.add(testscore4TF);
pane.add(weight1L);
pane.add(weight1TF);
pane.add(weight2L);
pane.add(weight2TF);
pane.add(weight3L);
pane.add(weight3TF);
pane.add(weight4L);
pane.add(weight4TF);
pane.add(calculateB);
pane.add(exitB);
//Set the window size
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHanlder implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double testscore1, testscore2, testscore3, testscore4;
double weight1, weight2, weight3, weight4;
double average1, average2, average3, average4;
double totalAverage;
testscore1 = Double.parseDouble(testscore1TF.getText());
testscore2 = Double.parseDouble(testscore2TF.getText());
testscore3 = Double.parseDouble(testscore3TF.getText());
testscore4 = Double.parseDouble(testscore4TF.getText());
weight1 = Double.parseDouble(weight1TF.getText());
weight2 = Double.parseDouble(weight2TF.getText());
weight3 = Double.parseDouble(weight3TF.getText());
weight4 = Double.parseDouble(weight4TF.getText());
average1 = testscore1 * weight1;
average2 = testscore2 * weight2;
average3 = testscore3 * weight3;
average4 = testscore4 * weight4;
totalAverage = average1 + average2 + average3 + average4;
scoreTF.setText("" + String.format("%,2f", totalAverage));
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
SNHU6_4 rectObject = new SNHU6_4();
}
}
CalculateButtonHandler cannot be resolved to a type
Is telling you it can't find a class by that name:
private class CalculateButtonHanlder implements ActionListener
You have a typo "Hanlder"
private class CalculateButtonHandler implements ActionListener
You spelled `CalculateButtonHandler' as 'CalculateButtonHanlder' when you declared the class on line 120. Fix that and it will work.

How to sum all sales through Jbutton clicks in Java?

I want to add the prices of each sale made using the calculate button and finally revealing it using a Total button. This button will give me all the sales made depending how many times I clicked the calculate button. I remember it was something like count++ or counter.
Here's what ive got.
public class OrderCalculatorGUI extends JFrame {
private BagelPanel bagels;
private ToppingPanel toppings;
private CoffeePanel coffee;
private GreetingPanel banner;
private JPanel buttonPanel;
private JButton calcButton;
private JButton exitButton;
private final double TAX_RATE = 0.06;
public OrderCalculatorGUI() {
setTitle("Order Calculator");
setLayout(new BorderLayout());
banner = new GreetingPanel();
bagels = new BagelPanel();
toppings = new ToppingPanel();
coffee = new CoffeePanel();
buildButtonPanel();
add(banner, BorderLayout.NORTH);
add(bagels, BorderLayout.WEST);
add(toppings, BorderLayout.CENTER);
add(coffee, BorderLayout.EAST);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
private void buildButtonPanel() {
buttonPanel = new JPanel();
calcButton = new JButton("Calculate");
exitButton = new JButton("Exit");
calcButton.addActionListener(new CalcButtonListener());
exitButton.addActionListener(new ExitButtonListener());
buttonPanel.add(calcButton);
buttonPanel.add(exitButton);
}
private class CalcButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double subtotal, tax, total;
subtotal = bagels.getBagelCost() + toppings.getToppingCost() + coffee.getCoffeeCost();
tax = subtotal * TAX_RATE;
total = subtotal + tax;
DecimalFormat dollar = new DecimalFormat("0.00");
JOptionPane.showMessageDialog(null, "Subtotal: $" + dollar.format(subtotal) + "\n" + "Tax: $" + dollar.format(tax) + "\n" + "Total: $" + dollar.format(total));
}
}

Trouble with integer validation and showing users have entered invalid data

This is for a Java program I'm working on as part of a homework assignment. I don't want the work done for me, but I'm stuck. I'm fairly new to Java, and using NetBeans IDE 7.0.1.
I'm having difficulty with some exception handling when trying to validate user input. This program will log charitable donations from user input. However, I've not been successful in validating the donation amount text field input. If a user inputs text instead of numbers, I would like them to be notified that their input was invalid, and I'd like the exception handling to handle the error and carry on after the user fixes their entry. Any help is greatly appreciated.
Here is my code:
package donorgui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 510;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Donor");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
// Create a panel.
panel = new JPanel();
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(exitButton);
panel.add(clearButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
donationAmt[i] = Double.parseDouble(pledgeField.getText());
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
i++;
}
}
public boolean donationAmt(String amount) {
int i = 0;
try {
i = Integer.parseInt (amount);
return true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid Input. Please enter a dollar amount");
return false;
}
}
private class ClearButtonListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
Here is my revised code. After some user input testing, I'm getting an exception when I use 100.00, 40.00, etc... instead of whole dollar amounts, such as 100, 40, etc.
Any thoughts?
package donorgui;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.io.*;
import java.awt.*;
public class DonorGUI extends JFrame
{
// Components
private JPanel panel;
private JTextArea results;
private JButton entryButton;
private JButton exitButton;
private JButton clearButton;
private JTextField donorField;
private JTextField charityField;
private JTextField pledgeField;
//create variables
String[] donorName = new String[20];
String[] charityName = new String[20];
double[] donationAmt = new double[20];
int i = 0;
// Constants for the window size
private final int WINDOW_WIDTH = 750;
private final int WINDOW_HEIGHT = 550;
//Constructor
public DonorGUI(){
// Set the title.
setTitle("Donor");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Add the panel to the content pane.
add(panel);
// Size and display the window.
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
//The buildPanel method creates a panel containing other components.
private void buildPanel(){
// Create labels to display instructions.
JLabel message1 = new JLabel("Name of the Donor:");
JLabel message2 = new JLabel("Name of the Charity:");
JLabel message3 = new JLabel("Amount of the Pledge:");
//instantiate the results area
results = new JTextArea(25,60);
// Create text fields to receive user input
donorField = new JTextField(10);
charityField = new JTextField(10);
pledgeField = new JTextField(10);
//create the user buttons to cause action
entryButton = new JButton("Enter Donation.");
entryButton.addActionListener(new EntryButtonListener());
exitButton = new JButton("EXIT");
exitButton.addActionListener(new ExitButtonListener());
clearButton = new JButton ("Clear Fields");
clearButton.addActionListener(new ClearButtonListener());
// Create a panel.
panel = new JPanel();
//set the LayoutManager
panel.setLayout(new FlowLayout());
// Add the labels, text fields, and button to the panel.
panel.add(message1);
panel.add(donorField);
panel.add(message2);
panel.add(charityField);
panel.add(message3);
panel.add(pledgeField);
panel.add(results);
panel.add(entryButton);
panel.add(exitButton);
panel.add(clearButton);
}
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if (donationAmt(pledgeField.getText())) {
donationAmt[i] = Double.parseDouble(pledgeField.getText());
}
results.append(donorName[i]+" "+charityName[i]+" "+donationAmt[i]+"\n ");
i++;
}
}
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //checking for empty field
JOptionPane.showMessageDialog(null, "Please enter a dollar amount");
return false;
}
for(int i = 0; i < amount.length(); i++){ //verifying dollar amount entered as number
if (!Character.isDigit(amount.charAt(i))){
JOptionPane.showMessageDialog(null, "Invalid input. Please enter a dollar amount");
return false;
}
}
return true;
}
private class ClearButtonListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
donorField.setText("");
charityField.setText("");
pledgeField.setText("");
}
}
private class ExitButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
/* Application method */
public static void main(String[] args){
DonorGUI rpc = new DonorGUI();
}
}
You can use InputVerifier, discussed here.
private class EntryButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
donorName[i] = donorField.getText();
charityName[i] = charityField.getText();
if(donationAmt(pledgeField.getText())){
donationAmt[i] = Double.parseDouble(pledgeField.getText());
results.append(donorName[i] + " " + charityName[i] + " " + donationAmt[i] + "\n ");
i++;
}
}
}
Something like this would work. This checks so that the amount is not empty and contains only digits based on your exisiting method.
public boolean donationAmt(String amount) {
if(amount==null || amount=="" || amount.length()<1){ //check so that the amount field is not empty, pherhaps you can add a check so the amound is not 0 :)
JOptionPane.showMessageDialog(null, "Invalid Input. The amount cannot be empty");
return false;
}
for(int i = 0; i < amount.length(); i++){ //loop thru the string and check so that each char is a digit
if (!Character.isDigit(amount.charAt(i))){
JOptionPane.showMessageDialog(null, "The amount can contain only numbers");
return false;
}
return true;
If you want to make sure that the amount is not 0, one approach would be to parse amount to int, and check so that parsedAmount<0. This should be done after it's verified that the amount is not empty and is only digits (e.i last:) ) to avoid NPE's and numberformatexception

Categories