Travel expenses GUI "Calculate reimbursement" button not responding - java

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.

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();
}
}

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.

Swing program exits immediately after starting

The program will launch but then immediately quit. Also, I'm not quite sure if adding multiple panels to a class that extends JFrame is allowed.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TravelExpensesCaskey extends JFrame
{
private double tripDays;
private double airfareCost;
private double carRentalFees;
private double numMiles;
private double parkingFees;
private double taxiCharges;
private double registrationFees;
private double lodgingCost;
private final double FOOD_$_PER_DAY = 37.00;
private final double PARKING_$_PER_DAY = 10.00;
private final double TAXI_$_PER_DAY = 20.00;
private final double LODGING_$_PER_DAY = 95.00;
private final double $_PER_MILE = 0.27;
private JPanel inputPanel;
private JPanel messageBar;
private JPanel panel;
private JPanel calculateBar;
private JButton calcButton;
private final int WINDOW_HEIGHT = 400;
private final int WINDOW_WIDTH = 200;
private JTextField field2;
private JTextField field3;
private JTextField field4;
private JTextField field5;
private JTextField field6;
private JTextField field7;
private JTextField field8;
private JTextField field9;
private double totalExpenditures;
private double totalAllowance;
private double totalBalance;
private double totalStipend;
public TravelExpensesCaskey()
{
setTitle("Travel Expenses");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label1 = new JLabel("Please input the following information about your trip. Enter 0 for any irrelavent values.");
messageBar = new JPanel();
messageBar.add(label1);
add(messageBar);
inputPanel.setLayout(new GridLayout(9,2));
inputPanel = buildPanel();
add(inputPanel);
calculateBar = buildCalculateBar();
add(calculateBar);
setVisible(true);
JOptionPane.showMessageDialog(null, "The total expenses incurred by the business person: " + totalExpenditures + "." +
"\nThe total allowance for the business person: " + totalAllowance + "." +
"\nThe total balance that must be paid for by the business person: " + totalBalance + "." +
"\nThe total stipend available to the business person: " + totalStipend + ".");
}
private JPanel buildPanel()
{
JLabel label2 = new JLabel("Number of Days: ");
JLabel label3 = new JLabel("Airfare Charges: :");
JLabel label4 = new JLabel("Car Rental Fees: ");
JLabel label5 = new JLabel("Number of Miles Driven: ");
JLabel label6 = new JLabel("Amount of Parking Fees: ");
JLabel label7 = new JLabel("Amount of Taxi Charges: ");
JLabel label8 = new JLabel("Conference/Seminar Registration Fees: ");
JLabel label9 = new JLabel("Lodging Charges per Night: ");
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
JPanel panel9 = new JPanel();
panel2.add(label2);
panel3.add(label3);
panel4.add(label4);
panel5.add(label5);
panel6.add(label6);
panel7.add(label7);
panel8.add(label8);
panel9.add(label9);
JTextField field2 = new JTextField(10);
JTextField field3 = new JTextField(10);
JTextField field4 = new JTextField(10);
JTextField field5 = new JTextField(10);
JTextField field6 = new JTextField(10);
JTextField field7 = new JTextField(10);
JTextField field8 = new JTextField(10);
JTextField field9 = new JTextField(10);
panel.add(panel2);
panel.add(field2);
panel.add(panel3);
panel.add(field3);
panel.add(panel4);
panel.add(field4);
panel.add(panel5);
panel.add(field5);
panel.add(panel6);
panel.add(field6);
panel.add(panel7);
panel.add(field7);
panel.add(panel8);
panel.add(field8);
panel.add(panel9);
panel.add(field9);
return panel;
}
private JPanel buildCalculateBar()
{
JPanel panel = new JPanel();
calcButton = new JButton("Calculate");
calcButton.addActionListener(new ButtonListener());
panel.add(calcButton);
return panel;
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String userText = "";
userText = field2.getText();
tripDays = Integer.parseInt(userText);
userText = field3.getText();
airfareCost = Integer.parseInt(userText);
userText = field4.getText();
carRentalFees = Integer.parseInt(userText);
userText = field5.getText();
numMiles = Integer.parseInt(userText);
userText = field6.getText();
parkingFees = Integer.parseInt(userText);
userText = field7.getText();
taxiCharges = Integer.parseInt(userText);
userText = field8.getText();
registrationFees = Integer.parseInt(userText);
userText = field9.getText();
lodgingCost = Integer.parseInt(userText);
calcCharges();
}
}
private void calcCharges()
{
totalExpenditures = (tripDays * lodgingCost) + parkingFees + airfareCost + carRentalFees + taxiCharges + registrationFees;
totalAllowance = (tripDays * FOOD_$_PER_DAY) + (tripDays + PARKING_$_PER_DAY) + (tripDays * TAXI_$_PER_DAY)
+ (tripDays * LODGING_$_PER_DAY) + (numMiles * $_PER_MILE);
if ((totalExpenditures - totalAllowance) < 0)
{
totalStipend = Math.abs(totalExpenditures - totalAllowance);
totalBalance = 0;
}
else if ((totalExpenditures - totalAllowance) > 0)
{
totalBalance = totalExpenditures - totalAllowance;
totalStipend = 0;
}
}
public static void main(String[] args)
{
new TravelExpensesCaskey();
}
}
Your program throw multiple NullPointerExceptions. You declare many objects as class fields and then never initialize them. You need to add at least:
inputPanel = new JPanel(); in constructor,
panel = new JPanel(); in buildPanel();
and in case of all yours JTextFields, change from:
JTextField field = new JTextField();
to:
field = new JTextField();
But it is only beginning because you GUI doesn't display most of components. You need to choose LayoutManager, and work with it. You add all your panels to center of your frames BorderLayout and I think they overlap . So for example, to see your JTextFields, JLabel and JButton, you can change add(component); in constructor for:
add(BorderLayout.NORTH, messageBar);
add(BorderLayout.CENTER, inputPanel);
add(BorderLayout.SOUTH,calculateBar);
also add:
panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS));
in buildPanel() method, and it will look better.
Whats more, you need to move code for JOptionPane to the end of calcCharges() method, this way it will have access to processed date and it will display proper output. At beginning of a app, it displays only zeros.

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));
}
}

class not retrieving information from another class

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

Categories