Related
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();
}
}
There was an error to this code which is:
private JLabel snL, fnL, mnL, gL, aL, adL, cnL, sbjL, aL, rL, tL, tfL;
private JTextField snTF, fnTF, mnTF, gTF, aTF, adTF, cnTF, sbjTF, aTF, rTF, tTF, tfTF;
This is the whole program.
import javax.swing.*;
import java.awt.*;
public class EnrollmentSystem2 extends JFrame
{
private static final int WIDTH = 500;
private static final int HEIGHT = 400;
private JLabel snL, fnL, mnL, gL, aL, adL, cnL, sbjL, aL, rL, tL, tfL;
private JTextField snTF, fnTF, mnTF, gTF, aTF, adTF, cnTF, sbjTF, aTF, rTF, tTF, tfTF;
public EnrollmentSystem2()
{
setTitle ("UPHSD Enrollment");
snL = new JLabel (" Surname:", SwingConstants.LEFT);
fnL = new JLabel (" First Name:", SwingConstants.LEFT);
mnL = new JLabel (" Middle Name:", SwingConstants.LEFT);
gL = new JLabel (" Gender:", SwingConstants.LEFT);
aL = new JLabel (" Age:", SwingConstants.LEFT);
adL = new JLabel (" Adress:", SwingConstants.LEFT);
cnL = new JLabel (" Contact No.:", SwingConstants.LEFT);
sbjL = new JLabel (" Suject:", SwingConstants.LEFT);
aL = new JLabel (" Assesstment:", SwingConstants.LEFT);
rL = new JLabel (" Room:", SwingConstants.LEFT);
tL = new JLabel (" Time:", SwingConstants.LEFT);
tfL = new JLabel (" Tuition fee:", SwingConstants.LEFT);
snTF = new JTextField (10);
fnTF = new JTextField (10);
mnTF = new JTextField (10);
gTF = new JTextField (10);
aTF = new JTextField (10);
adTF = new JTextField (10);
cnTF = new JTextField (10);
sbjTF = new JTextField (10);
aTF = new JTextField (10);
rTF = new JTextField (10);
tTF = new JTextField (10);
tfTF = new JTextField (10);
Container pane = getContentPane();
pane.setLayout (new GridLayout(9,2));
pane.add(snL);
pane.add(snTF);
pane.add(fnL);
pane.add(fnTF);
pane.add(mnL);
pane.add(mnTF);
pane.add(gL);
pane.add(gTF);
pane.add(aL);
pane.add(aTF);
pane.add(adL);
pane.add(adTF);
pane.add(cnL);
pane.add(cnTF);
pane.add(sbjL);
pane.add(sbjTF);
pane.add(aL);
pane.add(aTF);
pane.add(rL);
pane.add(rTF);
pane.add(tL);
pane.add(tTF);
pane.add(tfL);
pane.add(tfTF);
setSize(WIDTH, HEIGHT);
setVisible (true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
public static void main (String[]args)
{
EnrollmentSystem2 Object = new EnrollmentSystem2();
}
}
You have declared two labels with name aL. Every variable must have a unique name.
Edit: the same with aTF
btw, your import statements should be:
import javax.swing.*;
import java.awt.*;
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.
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();
}
}
Try running my program. Press Add Subject (fill the data). Then Display. Then Add another subject. Then Display.
On the Display Tab, it shows 2 subjects and 1 empty subject.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
#SuppressWarnings ({"unchecked" , "rawtypes"})
public class StudentGradeCalc extends JFrame implements ActionListener {
//String setName [];
int x = 0;
int count = 0;
int w = 0;
int [] addSize = {50,10,20,30,40,100};
private JPanel panelInfo = new JPanel(new GridLayout(7,0) );
private JLabel sy = new JLabel ("School Year : ");
private JLabel sem = new JLabel ("Sem/Term: ");
private JLabel Name = new JLabel ("Name : ");
private JLabel Course = new JLabel ("Course : ");
private JLabel Year = new JLabel ("Year : ");
private JLabel college = new JLabel ("College : ");
private JLabel id = new JLabel ("I.D Number : ");
private JTextField syear = new JTextField ("");
private JTextField semnum = new JTextField("");
private JTextField name = new JTextField ("");
private JTextField course = new JTextField ("");
private JTextField year = new JTextField ("");
private JTextField scs = new JTextField("");
private JTextField idnum = new JTextField("");
private JPanel fakebuttons = new JPanel (new GridLayout (4,0,10,10));
private JButton addSubject = new JButton("Add Subject..");
private JButton deleteSubject = new JButton("Delete Subject..");
private JButton editSubject = new JButton("Edit Subject..");
private JButton totalLoad = new JButton("Total Load : ");
private JButton GPA = new JButton ("GPA : ");
private JTextField units_textfield = new JTextField(3);
private JTextField gpa_textfield = new JTextField (7);
private JButton displayInfo = new JButton("Display Data");
private JPanel addPanel = new JPanel(new GridLayout(3,2,20,10));
private JLabel subjectName = new JLabel("Subject: ");
private JTextField subject [] ;
private JLabel gradeLabel = new JLabel("Grade : ");
private JLabel unitsLabel = new JLabel ("Units : ");
private JButton addButton = new JButton ("Add");
String grade [] = {"1.00","1.25","1.50","1.75","2.00","2.25","2.50","2.75","3.00","5.0", "DRP", "INC", "WDRW"};
private JComboBox comboGrade [];
String unit [] = {"1","2","3","4","5","6"};
private JComboBox comboUnit[];
private JButton done = new JButton ("Done");
private JButton d_subj,d_unit,d_grade;
// private JTextField displaySubject = new JTextField();
// private JTextField displayUnit = new JTextField ();
//private JTextField displayGrade = new JTextField();
private JTextField displaySubject[];
private JTextField displayUnit[];
private JTextField displayGrade [];
private JLabel t_units = new JLabel ("Total Load : ");
private JTextField totalUnits = new JTextField ();
private JLabel gpa = new JLabel ("GPA : ");
private JTextField gpaTxt = new JTextField ();
private JLabel err = new JLabel ("No Entry Found");
private JLabel display1 = new JLabel ();
private JLabel display2 = new JLabel ();
private JLabel displayID = new JLabel ();
final String getName [] = new String [10];
final int getUnit [] = new int [10];
final String getGrade [] = new String [10];
public StudentGradeCalc()
{
Border border = BorderFactory.createLineBorder(null);
setLayout(null);
panelInfo.setBounds(5,5,280,150);
//panelInfo.setBorder(border);
panelInfo.add(Name);
panelInfo.add(name);
panelInfo.add(Course);
panelInfo.add(course);
panelInfo.add(Year);
panelInfo.add(year);
panelInfo.add(sy);
panelInfo.add(syear);
panelInfo.add(sem);
panelInfo.add(semnum);
panelInfo.add(college);
panelInfo.add(scs);
panelInfo.add(id);
panelInfo.add(idnum);
add(panelInfo);
fakebuttons.setBounds(5,160,280,160);
fakebuttons.add(addSubject);
fakebuttons.add(deleteSubject);
fakebuttons.add(editSubject);
fakebuttons.add(displayInfo);
add(fakebuttons);
//ADD SUBJECT BUTTON
addSubject.addActionListener(new ActionListener (){
public void actionPerformed (ActionEvent cags){
final JFrame addFrame = new JFrame ();
addFrame.setVisible(true);
addFrame.setSize (300,190);
addFrame.setResizable(false);
addFrame.setLocationRelativeTo(null);
addFrame.setTitle("Add Subject");
//addFrame.setLayout(new GridLayout (3,2,20,10));
addFrame.setLayout(null);
subject = new JTextField [] {
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
new JTextField (),
};
subjectName.setBounds (10,10,120,20);
subject[x].setBounds (75,10,170,20);
addFrame.add(subjectName);
addFrame.add(subject[x]);
gradeLabel.setBounds (10,40,100,20);
addFrame.add(gradeLabel);
comboGrade = new JComboBox [] {
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
new JComboBox (grade),
};
comboGrade[x].setBounds(150,40,95,20);
addFrame.add(comboGrade[x]);
unitsLabel.setBounds (10, 70, 95, 20);
addFrame.add(unitsLabel);
comboUnit = new JComboBox [] {
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
new JComboBox(unit),
};
comboUnit[x].setBounds(150,70,95,20);
addFrame.add(comboUnit[x]);
addButton.setBounds (120,120,60,30);
addFrame.add(addButton);
w++;
addButton.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent k){
//JOptionPane.showMessageDialog(null, "Subject "+subject[x].getText()+ " has been added", "Add Subject", JOptionPane.INFORMATION_MESSAGE);
getName [x] = subject[x].getText();
getGrade[x] = String.valueOf((String)comboGrade[x].getSelectedItem());
getUnit [x] = Integer.valueOf((String)comboUnit[x].getSelectedItem());
x++;
addFrame.dispose();
}
});
}
});
//DISPLAY DATA BUTTON
displayInfo.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent m){
final String name_course_year = "Name : "+name.getText()+ " Course : " +course.getText()+"- "+year.getText()+ " ID : "+idnum.getText() ;
final String ubos = "College : "+scs.getText()+ " SY : "+syear.getText()+ " Term : "+semnum.getText() ;
//String nametanga [] = {name.getText() , };
if (name.getText().equals("")|| course.getText().equals("")||year.getText ().equals("") || idnum.getText().equals("")||syear.getText ().equals("") || scs.getText().equals("")|| semnum.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Complete the Information!", "ERROR", JOptionPane.WARNING_MESSAGE);
}
else
{
final JFrame display = new JFrame ();
display.setVisible(true);
//display.setSize (400,200);
//display.setSize (400,down+130);
display.setResizable(false);
display.setLocationRelativeTo(null);
display.setTitle("Student Info");
display.setLayout(null);
display1.setBounds (5,5,390,20);
display2.setBounds (5,25,390,20);
display1.setText(name_course_year);
display2.setText(ubos);
display.add(display1);
display.add(display2);
d_subj = new JButton ("Subject");
d_unit = new JButton ("Unit");
d_grade = new JButton ("Grade");
d_subj.setBounds(10,50,180,20);
d_unit.setBounds (200,50,90,20);
d_grade.setBounds(300,50,90,20);
display.add(d_subj);
display.add(d_unit);
display.add(d_grade);
displaySubject = new JTextField [] {
new JTextField(),
new JTextField(),
new JTextField(),
new JTextField(),
new JTextField(),
new JTextField(),
new JTextField(),
};
displayUnit = new JTextField [] {
new JTextField(),new JTextField(),new JTextField(),
new JTextField(),new JTextField(),new JTextField(),
new JTextField(),new JTextField(),
};
displayGrade = new JTextField [] {
new JTextField(),new JTextField(),new JTextField(),
new JTextField(),new JTextField(),new JTextField(),
new JTextField(),new JTextField(),
};
int y = 30;
int down = 80;
int z = 0;
for (int i = 0; i < x; i++)
{
displaySubject[i].setBounds(10,down,180,y);
displayUnit[i].setBounds(200,down,90,y);
displayGrade[i].setBounds(300,down,90,y);
displaySubject[i].setText(getName[i]);
displayUnit[i].setText(""+getUnit[i]);
displayGrade[i].setText(getGrade[i]);
display.add(displaySubject[i]);
display.add(displayUnit[i]);
display.add(displayGrade[i]);
displaySubject[i].setEditable(false);
displayUnit[i].setEditable(false);
displayGrade[i].setEditable(false);
down+=y+10;
//i++;
// z++;
}
display.setSize (400,down+130);
t_units.setBounds (100,down,70,25);
totalUnits.setBounds(180,down,50,25);
gpa.setBounds(260,down,50,25);
gpaTxt.setBounds(310,down,80,25);
display.add(t_units);
display.add(totalUnits);
display.add(gpa);
display.add(gpaTxt);
gpaTxt.setEditable(false);
totalUnits.setEditable(false);
done.setBounds (170,down+50,70,30);
display.add(done);
done.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent done){
display.dispose();
}
});
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize (300,355);
setResizable(false);
setLocationRelativeTo(null);
setTitle("Student Grade Calculator");
}
public void actionPerformed (ActionEvent vahn)
{
System.exit(1);
}
public static void main(String[] args) {
new StudentGradeCalc();
}
}
I do not know where to find the reason why my program makes this error.
I found your problem it's here addButton.addActionListener(). You always add a new ActionListener to your button instance, because of that, every time you push addSubject button you also add a new Listener to addButton. Don't do that in the future, add your Listeners to Components, in method of component construction.