Double cannot be converted to JTextField - java

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

Related

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.

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.

Java - GUI: Passing values from frame to another

I am making a panel project that calls three panels. Panel one holds all information and the other two panels are panels that open up when I press a button. How it works is I call the first panel, press a button, second panel opens. Then in the second panel I plug in a password. If it is correct, a third panel will open. I need to call values from the first panel into the third panel. I know how to use constructors, accessors and mutators, but the values I need are generated in an event when I press a button. I am trying to figure out how to call those values from the event into the third panel. Essentially, the values are counters, sub-total, tax, and total for all transactions of the duration of the program. Here is my code.
Main Class:
import javax.swing.*;
public class AppleRegister {
public static void main(String[] args)
{
double subTotalp2 = 0, taxP2 = 0, realTotalp2 = 0;
JFrame frame = new JFrame("Apple Crazy Cola Cash (Apple IIC) Register");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AppleRegisterPanel panel = new AppleRegisterPanel
(subTotalp2, taxP2, realTotalp2);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
First Panel:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;
public class AppleRegisterPanel extends JPanel
{
private JButton button1, button2, button3, button4, button5, button6;
private JLabel label1, label2, label3, label4, label5, label6, label7;
private JTextField text, text1, text2, text3, text4, text5, text6, text7, text8;
private JTextArea area ;
private JPanel panel, panel2, panel3, panel4;
private int counter, counter2, counter3, counter4, counterp21, counterp22,
counterp23, counterp24;
private String string;
private final double MD_TAX = 0.06;
private double subTotal, realTotal, tax, subTotalp2, realTotalp2, taxP2;
private double num100, num50, num20, num10, num5, num1, num25cents, num10cents,
num5cents, num1cents;
public AppleRegisterPanel(double subTotalp2, double taxP2, double realTotalp2)
{
this.subTotalp2 = subTotalp2;
this.taxP2 = taxP2;
this.realTotalp2 = realTotalp2;
setLayout(new BorderLayout());
text = new JTextField(10);
text1 = new JTextField(5);
text2 = new JTextField(5);
text3 = new JTextField(5);
text4 = new JTextField(5);
text5 = new JTextField(10);
text6 = new JTextField(10);
text7 = new JTextField(10);
text8 = new JTextField(10);
area = new JTextArea();
button1 = new JButton("Child");
button2 = new JButton("Medium");
button3 = new JButton("Large");
button4 = new JButton("Ex Large");
button5 = new JButton("Close Out Register");
button6 = new JButton("Complete Transaction");
panel = new JPanel();
panel.setPreferredSize(new Dimension(240,250));
panel.setBackground(Color.cyan);
add(panel, BorderLayout.WEST);
panel.add(button1);
button1.addActionListener(new TempListener2());
panel.add(text1);
panel.add(Box.createRigidArea(new Dimension(0,20)));
panel.add(button2);
button2.addActionListener(new TempListener2());
panel.add(text2);
panel.add(Box.createRigidArea(new Dimension(0,20)));
panel.add(button3);
button3.addActionListener(new TempListener2());
panel.add(text3);
panel.add(Box.createRigidArea(new Dimension(0,20)));
panel.add(button4);
button4.addActionListener(new TempListener2());
panel.add(text4);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel2 = new JPanel();
label6 = new JLabel("Change");
panel2.setPreferredSize(new Dimension(270,250));
panel2.setBackground(Color.cyan);
add(panel2, BorderLayout.EAST);
panel2.add(button5);
button5.addActionListener(new TempListener());
panel2.add(label6);
panel2.add(area);
panel2.add(button6);
button6.addActionListener(new TempListener1());
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
panel3 = new JPanel();
label1 = new JLabel("Apple Crazy Cola Cash (Apple IIC) Register ");
label7 = new JLabel(" By Robert Burns");
panel3.setPreferredSize(new Dimension(50,50));
panel3.setBackground(Color.cyan);
add(panel3, BorderLayout.NORTH);
panel3.add(label1);
panel3.add(label7);
panel4 = new JPanel();
label1 = new JLabel("Sub-Total");
label2 = new JLabel("Tax");
label3 = new JLabel("Total");
label4 = new JLabel("Payment");
label5 = new JLabel("Change Owed");
panel4.setPreferredSize(new Dimension(140,250));
panel4.setBackground(Color.cyan);
add(panel4, BorderLayout.CENTER);
panel4.add(label1);
panel4.add(text);
panel4.add(label2);
panel4.add(text5);
panel4.add(label3);
panel4.add(text6);
panel4.add(label4);
panel4.add(text7);
text7.addActionListener(new TempListener3());
panel4.add(label5);
panel4.add(text8);
}
private class TempListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == button5)
{
JFrame frame3 = new JFrame("Apple Crazy Cola Cash (Apple
IIC) Register");
frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AppleRegisterPanel3 panel = new AppleRegisterPanel3();
frame3.getContentPane().add(panel);
frame3.pack();
frame3.setVisible(true);
}
}
}
private class TempListener1 implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == button6)
{
counter = 0;
text1.setText(Integer.toString(counter));
counter2 = 0;
text2.setText(Integer.toString(counter2));
counter3 = 0;
text3.setText(Integer.toString(counter3));
counter4 = 0;
text4.setText(Integer.toString(counter4));
subTotal = 0;
text.setText(Double.toString(subTotal));
tax = 0;
text5.setText(Double.toString(tax));
realTotal = 0;
text6.setText(Double.toString(realTotal));
text7.setText("");
text8.setText("");
}
}
}
private class TempListener2 implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
DecimalFormat df = new DecimalFormat("#.##");
if (event.getSource() == button1)
{
counter++;
string = text1.getText();
text1.setText(Integer.toString(counter));
subTotal += counter * 0.90;
string = text.getText();
text.setText(df.format(subTotal));
tax += subTotal * MD_TAX;
string = text5.getText();
text5.setText(df.format(tax));
realTotal += subTotal + tax;
string = text6.getText();
text6.setText(df.format(realTotal));
counterp21++;
subTotalp2 += counterp21 * 0.90;
taxP2 += subTotalp2 * MD_TAX;
realTotalp2 += subTotalp2 * taxP2;
}
if (event.getSource() == button2)
{
counter2++;
string = text2.getText();
text2.setText(Integer.toString(counter2));
subTotal += counter2 * 1.40;
string = text.getText();
text.setText(df.format(subTotal));
tax += subTotal * MD_TAX;
string = text5.getText();
text5.setText(df.format(tax));
realTotal += subTotal + tax;
string = text6.getText();
text6.setText(df.format(realTotal));
counterp22++;
subTotalp2 += counterp22 * 1.40;
taxP2 += subTotalp2 * MD_TAX;
realTotalp2 += subTotalp2 * taxP2;
}
if (event.getSource() == button3)
{
counter3++;
string = text3.getText();
text3.setText(Integer.toString(counter3));
subTotal += counter3 * 1.75;
string = text.getText();
text.setText(df.format(subTotal));
tax += subTotal * MD_TAX;
string = text5.getText();
text5.setText(df.format(tax));
realTotal += subTotal + tax;
string = text6.getText();
text6.setText(df.format(realTotal));
counterp23++;
subTotalp2 += counterp23 * 1.75;
taxP2 += subTotalp2 * MD_TAX;
realTotalp2 += subTotalp2 * taxP2;
}
if (event.getSource() == button4)
{
counter4++;
string = text4.getText();
text4.setText(Integer.toString(counter4));
subTotal += counter4 * 2.00;
string = text.getText();
text.setText(df.format(subTotal));
tax += subTotal * MD_TAX;
string = text5.getText();
text5.setText(df.format(tax));
realTotal += subTotal + tax;
string = text6.getText();
text6.setText(df.format(realTotal));
counterp24++;
subTotalp2 += counterp24 * 2.00;
taxP2 += subTotalp2 * MD_TAX;
realTotalp2 += subTotalp2 * taxP2;
}
}
}
If you scroll down to TempListner2 and see the variables subTotalp2, taxP2, realTotalp2; those are the variables I need to carry over. You'll see that I made the constructor have those variables in it so I can call the methods over in the third panel, but no dice. Comes up 0.0 when I open the third panel. Not sure if it is because it is in a void event or not. I'll post part of the third panel here where I am trying to call the constructor from the first panel and inset the values into the third.
Third Panel:
public AppleRegisterPanel2()
{
AppleRegisterPanel p = new AppleRegisterPanel(subTotalp2, taxP2,
realTotalp2);
this.subTotalp2 = subTotalp2;
this.taxP2 = taxP2;
this.realTotalp2 = realTotalp2;
subTotalp2 = p.getSubTotal();
taxP2 = p.getTax();
realTotalp2 = p.getTotal();
You'll see here that I am trying a weird ass way to call the values.
One problem is that you're opening another JFrame from a JFrame, when you should instead be displaying a modal JDialog. The reason for this is that you cannot advance your program until the user enters the appropriate information, and so the 2nd window should be modal which will prevent interaction with the underlying window until the dialog window has been completely dealt with. If you do this, and place your JPanel into a modal JDialog, then you can easily query the results from the 2nd JPanel because you will know in your code exactly when it's been dealt with -- your main GUI code resumes exactly from where you set the modal dialog visible.
For example:
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WindowCommunication {
private static void createAndShowUI() {
JFrame frame = new JFrame("WindowCommunication");
frame.getContentPane().add(new MyFramePanel());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// let's be sure to start Swing on the Swing event thread
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyFramePanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton openDialogeBtn = new JButton("Open Dialog");
// here my main gui has a reference to the JDialog and to the
// MyDialogPanel which is displayed in the JDialog
private MyDialogPanel dialogPanel = new MyDialogPanel();
private JDialog dialog;
public MyFramePanel() {
openDialogeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openTableAction();
}
});
field.setEditable(false);
field.setFocusable(false);
add(field);
add(openDialogeBtn);
}
private void openTableAction() {
// lazy creation of the JDialog
if (dialog == null) {
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
dialog = new JDialog(win, "My Dialog",
ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
}
dialog.setVisible(true); // here the modal dialog takes over
// this line starts *after* the modal dialog has been disposed
// **** here's the key where I get the String from JTextField in the GUI held
// by the JDialog and put it into this GUI's JTextField.
field.setText(dialogPanel.getFieldText());
}
}
class MyDialogPanel extends JPanel {
private JTextField field = new JTextField(10);
private JButton okButton = new JButton("OK");
public MyDialogPanel() {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButtonAction();
}
});
add(field);
add(okButton);
}
// to allow outside classes to get the text held by the JTextField
public String getFieldText() {
return field.getText();
}
// This button's action is simply to dispose of the JDialog.
private void okButtonAction() {
// win is here the JDialog that holds this JPanel, but it could be a JFrame or
// any other top-level container that is holding this JPanel
Window win = SwingUtilities.getWindowAncestor(this);
if (win != null) {
win.dispose();
}
}
}

Debugging code I have with 2 classes and a JFrame that holds 4 JPanels

I am looking for help to debug this program that I have written there are, no errors but the goal is to create a frame with three panels inside of it each of which has a titled border. I am having difficulty because my prompt requires of me to make 2 constructors and 2 classes so when I call the DailySales class in main I feel it doesn't include the other class.
So basically how can I make the panels show up while still keeping two classes and two constructors and how would I add titled borders to each of the JPanels, sorry but I'm having difficulty with the Oracle tutorial.
import java.awt.*;
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.JPanel;
import javax.swing.JTextField;
public class DailySales extends JPanel {
final int lPizzaPrice = 12;
final int mPizzaPrice = 9;
final int sPizzaPrice = 6;
final int bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza;
String mPizza;
String sPizza;
String bSticks;
int largePizza;
int mediumPizza;
int smallPizza;
int breadSticks;
int totalLargePizza;
int totalMediumPizza;
int totalSmallPizza;
int totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
private FlowLayout dailyFlow;
private Container container;
JLabel lPizzaLabel = new JLabel("Large Pizza");//creating labels
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");//Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(dailyFlow);
subPanel1.add(lPizzaLabel, largeField);
subPanel1.add(mPizzaLabel, mediumField);
subPanel1.add(sPizzaLabel, smallField);
subPanel1.add(bSticksLabel, breadField);
subPanel1.setSize(100, 100);
subPanel2.setLayout(dailyFlow);
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel3.setLayout(dailyFlow);
subPanel3.add(totalSalesLabel, totalSalesField);
subPanel3.add(totalTaxLabel, totalTaxField);
subPanel3.add(netSalesLabel, netSalesField);
subPanel3.add(dailyCostLabel, dailyCostField);
subPanel3.add(profitLabel, profitField);
top.setBackground(Color.red);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
totalSalesField.setEditable(false);//making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() //creating a constructor
{
/**
* The constructor with all the layout informations and operators
*
*
* Also adding all labels, textfields, and buttons to frame. making the
* total field uneditable
*/
JFrame frame = new JFrame();
frame.add(subPanel1);
frame.add(subPanel2);
frame.add(subPanel3);
frame.add(top);
frame.setSize(600, 450);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {//initial button removes all entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {//update button calculates all the inputs and displays everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice * largePizza);
totalMediumPizza = (mPizzaPrice * mediumPizza);
totalSmallPizza = (sPizzaPrice * smallPizza);
totalBreadSticks = (bSticksPrice * breadSticks);
totalLargeField.setText("" + totalLargePizza);
totalMediumField.setText("" + totalMediumPizza);
totalSmallField.setText("" + totalSmallPizza);
totalBreadField.setText("" + totalBreadSticks);
totalSales = (totalLargePizza + totalMediumPizza + totalSmallPizza + totalBreadSticks);
totalTax = (totalSales * tax);
netSales = (totalSales - totalTax);
profit = (netSales - dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit > 0) {
profitLabel.setText("Profit of ");
} else if (profit < 0) {
profitLabel.setText("Loss of ");
} else if (profit == 0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {//close button closes the program when clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
There's still a lot you can do to make this better, but this works.
public class DailySales extends JPanel {
final int lPizzaPrice = 12, mPizzaPrice = 9, sPizzaPrice = 6, bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza, mPizza, sPizza, bSticks;
int largePizza, mediumPizza, smallPizza, breadSticks, totalLargePizza,
totalMediumPizza, totalSmallPizza, totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
JLabel lPizzaLabel = new JLabel("Large Pizza");
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");// Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(new GridLayout(4, 2));
subPanel1.add(lPizzaLabel);
subPanel1.add(largeField);
subPanel1.add(mPizzaLabel);
subPanel1.add(mediumField);
subPanel1.add(sPizzaLabel);
subPanel1.add(smallField);
subPanel1.add(bSticksLabel);
subPanel1.add(breadField);
subPanel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
// subPanel2.setLayout(new BoxLayout(subPanel2, BoxLayout.Y_AXIS)); // Same as next line
subPanel2.setLayout(new GridLayout(4, 1));
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
subPanel3.setLayout(new GridLayout(5, 2));
subPanel3.add(totalSalesLabel);
subPanel3.add(totalSalesField);
subPanel3.add(totalTaxLabel);
subPanel3.add(totalTaxField);
subPanel3.add(netSalesLabel);
subPanel3.add(netSalesField);
subPanel3.add(dailyCostLabel);
subPanel3.add(dailyCostField);
subPanel3.add(profitLabel);
subPanel3.add(profitField);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
top.setBackground(Color.YELLOW);
totalSalesField.setEditable(false);// making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() // creating a constructor
{
/**
* The constructor with all the layout informations and operators Also
* adding all labels, textfields, and buttons to frame. making the total
* field uneditable
*/
new GUI();
JPanel mainPanel = new JPanel(new GridLayout(2, 2));
mainPanel.add(subPanel1);
mainPanel.add(subPanel2);
mainPanel.add(subPanel3);
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearButton);
buttonPanel.add(calculateButton);
buttonPanel.add(exitButton);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(top, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(600, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {// initial button
// removes all
// entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {// update button
// calculates
// all the
// inputs and
// displays
// everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice*largePizza);
totalMediumPizza = (mPizzaPrice*mediumPizza);
totalSmallPizza = (sPizzaPrice*smallPizza);
totalBreadSticks = (bSticksPrice*breadSticks);
totalLargeField.setText(""+totalLargePizza);
totalMediumField.setText(""+totalMediumPizza);
totalSmallField.setText(""+totalSmallPizza);
totalBreadField.setText(""+totalBreadSticks);
totalSales = (totalLargePizza+totalMediumPizza+totalSmallPizza+totalBreadSticks);
totalTax = (totalSales*tax);
netSales = (totalSales-totalTax);
profit = (netSales-dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit>0) {
profitLabel.setText("Profit of ");
} else if (profit<0) {
profitLabel.setText("Loss of ");
} else if (profit==0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {// close button
// closes the
// program when
// clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}

Categories