Calculating the total price - java

How do you calculate the total price of of groceries purchased? At the moment, I can only calculate only one of the grocery with its quantity.
Below are the classes that I have used:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
/**
Long Distance Calls
*/
public class GroceryMain extends JFrame
{
private RatePanel ratePanel; // A panel for rates
private QuantityPanel quantityPanel; // A panel for minutes
private JPanel buttonPanel; // A panel for the buttons
private JButton calcButton; // Calculates everything
private JButton exitButton; // Exits the application
/**
Constructor
*/
public GroceryMain()
{
// Display a title.
setTitle("Grocery Shop");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a RatePanel object.
ratePanel = new RatePanel();
// Create a MinutesPanel object.
quantityPanel = new QuantityPanel();
// Build the panel that contains the buttons.
buildButtonPanel();
// Add the panels to the content pane.
add(ratePanel, BorderLayout.WEST);
add(quantityPanel, 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("Calculate 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 rate; // Applicable rate
double totalCharges; // Total charges
// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Get the applicable rate.
rate = ratePanel.getRate();
// Get the total charges
totalCharges = quantityPanel.getCharges(rate);
// Display the message.
JOptionPane.showMessageDialog(null, "Total Charges: £" +
dollar.format(totalCharges));
}
} // 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 LongDistance
class, causing it to display its window.
*/
public static void main(String[] args)
{
GroceryMain ld = new GroceryMain();
}
}
import java.awt.*;
import javax.swing.*;
/**
MinutesPanel class
Long Distance Calls
*/
public class QuantityPanel extends JPanel
{
private JTextField quantity; // To get minutes
private JTextField quantity2; // To get minutes
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
/**
Constructor
*/
public QuantityPanel()
{
// Create a label prompting the user and a text field.
//JLabel minutesMsg = new JLabel("Quantity:");
quantity = new JTextField(5);
quantity2 = new JTextField(5);
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");
// Create a GridLayout manager.
setLayout(new GridLayout(15, 1));
// Create a border.
setBorder(BorderFactory.createTitledBorder("QTY"));
// Add the labels and text fields to this panel.
//add(minutesMsg);
//add(quantity);
// add(quantity2);
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);
}
/**
The getCharges method uses the specified rate to calculate
the charges for the number of minutes entered.
#param rate The per-minute rate.
#return The charges for the number of minutes used.
*/
public double getCharges(double rate)
{
double charges = Double.parseDouble(baked_beans_JT.getText()) * rate;
return charges;
}
}
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
/**
RatePanel class
Long Distance Calls
*/
public class RatePanel extends JPanel
{
// Named constants for rates
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 SAUSAGES = 1.30;
private final double EGGS = 0.75;
private final double MILK = 0.65;
private final double POTATOES = 2.00;
private JCheckBox bakedbeans; // Radio button for daytime rate
private JCheckBox cornflakes; // Radio button for evening rate
private JCheckBox sugar; // Radio button for off peak rate
private JCheckBox teabags; // Radio button for off peak rate
private JCheckBox instantcoffee; // Radio button for off peak rate
private JCheckBox bread; // Radio button for off peak rate
private JCheckBox sausages; // Radio button for off peak rate
private JCheckBox eggs; // Radio button for off peak rate
private JCheckBox milk; // Radio button for off peak rate
private JCheckBox potatoes; // Radio button for off peak rate
//private ButtonGroup bg; // Radio button group
/**
Constructor
*/
public RatePanel()
{
// Create a DecimalFormat object.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Create the check boxes.
bakedbeans = new JCheckBox("Bakedbeans (£" +
dollar.format(BAKED_BEANS) + " per packet)");
cornflakes = new JCheckBox("Cornflakes (£" +
dollar.format(CORNFLAKES) + " per packet)");
sugar = new JCheckBox("Sugar (£" +
dollar.format(SUGAR) + " per packet)");
teabags = new JCheckBox("Teabags (£" +
dollar.format(TEA_BAGS) + " per item)");
instantcoffee = new JCheckBox("Instantcoffee (£" +
dollar.format(INSTANT_COFFEE) + " per packet)");
bread = new JCheckBox("Bread (£" +
dollar.format(BREAD) + " per packet)");
sausages = new JCheckBox("Sausages (£" +
dollar.format(SAUSAGES) + " per packet)");
eggs = new JCheckBox("Eggs (£" +
dollar.format(EGGS) + " per packet)");
milk = new JCheckBox("Milk (£" +
dollar.format(MILK) + " per packet)");
potatoes = new JCheckBox("Potatoes (£" +
dollar.format(POTATOES) + " per packet)");
// Create a GridLayout manager.
setLayout(new GridLayout(15, 12));
// Create a border.
setBorder(BorderFactory.createTitledBorder("Select a Category"));
// Add the check boxes to this panel.
add(bakedbeans);
add(cornflakes);
add(sugar);
add(teabags);
add(instantcoffee);
add(bread);
add(sausages);
add(eggs);
add(milk);
add(potatoes);
}
/**
The getRate method returns the rate for the selected
rate category.
#return One of the constants DAYTIME_RATE, EVENING_RATE, or
OFF_PEAK_RATE.
*/
public double getRate()
{
double rate = 0.0;
if (bakedbeans.isSelected())
rate += BAKED_BEANS;
if (cornflakes.isSelected())
rate = CORNFLAKES;
else if (sugar.isSelected())
rate += SUGAR;
else if (teabags.isSelected())
rate += TEA_BAGS;
else if (instantcoffee.isSelected())
rate += INSTANT_COFFEE;
else if (bread.isSelected())
rate += BREAD;
else if (sausages.isSelected())
rate += SAUSAGES;
else if (eggs.isSelected())
rate += EGGS;
else if (milk.isSelected())
rate += MILK;
else if (potatoes.isSelected())
rate += POTATOES;
return rate;
}
}
I want to be able to calculate the total price of groceries when the user select a multiple of check-boxes with its quantities..

Try if - if instead of if-else if.
if - else if condition is satisfied, the appropriate statements are executed and the remaining conditions are not evaluated.
if -if will evaluate each condition.
public double getRate()
{
double rate = 0.0;
if (bakedbeans.isSelected())
rate += BAKED_BEANS;
if (cornflakes.isSelected())
rate += CORNFLAKES;
if (sugar.isSelected())
rate += SUGAR;
if (teabags.isSelected())
rate += TEA_BAGS;
if (instantcoffee.isSelected())
rate += INSTANT_COFFEE;
if (bread.isSelected())
rate += BREAD;
if (sausages.isSelected())
rate += SAUSAGES;
if (eggs.isSelected())
rate += EGGS;
if (milk.isSelected())
rate += MILK;
if (potatoes.isSelected())
rate += POTATOES;
return rate;
}

As I understand it, getCharges is intended to return the total cost of the selected items. The current implementation is:
public double getCharges(double rate)
{
double charges = Double.parseDouble(baked_beans_JT.getText()) * rate;
return charges;
}
Unfortunately, you cannot use the number of baked beans selected to predict what else the customer is buying :)
There are several ways this could be fixed, and I'm afraid all of them will need modifications elsewhere in the code. I would recommend looking into the use of arrays. If you'd rather avoid that, you'll have to do something similar to this:
double charges = 0;
charges += Integer.parseInt(baked_beans_JT.getText()) * BAKED_BEANS;
charges += Integer.parseInt(cornflakes_JT.getText()) * CORNFLAKES;
...
Since the getRate method wouldn't be needed anymore, you could adapt that and save some copy-pasting.
But really, look into arrays or collections. Without them, you're in for a frustrating future.

Related

Trying to figure out how to error handler into this candy machine program

Got this program for a candy machine GUI finished, but I can't figure out where to put in the InputMismatchException code. I've tried putting it in under the input for entering the payments, but I can't find a way to put it in the right area, I don't know what I'm doing wrong.
Main Candy Machine Class
import java.awt.Container;
import java.awt.GridLayout;
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.SwingConstants;
import java.util.InputMismatchException;
public class candyMachine extends JFrame {
//window size setup
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
//setup for the store items and register
private CashRegister cashRegister = new CashRegister();
private Dispenser candy = new Dispenser(100, 50);
private Dispenser chips = new Dispenser(100, 65);
private Dispenser gum = new Dispenser(75, 45);
private Dispenser cookies = new Dispenser(100, 85);
//heading and button setups
private JLabel headingMainL;
private JLabel selectionL;
private JButton exitB, candyB, chipsB, gumB, cookiesB;
private ButtonHandler pbHandler;
//the main machine constructor
public candyMachine() {
setTitle("Candy Machine"); // window title
setSize(WIDTH, HEIGHT); // window size
Container pane = getContentPane(); //container get
pane.setLayout(new GridLayout(7,1)); //pane layout setup
pbHandler = new ButtonHandler(); //instantiate listener object
//Store sign setup
headingMainL = new JLabel("WELCOME TO SHELLY'S CANDY SHOP", SwingConstants.CENTER);
//instructions setup
selectionL = new JLabel("To Make a Selection, " + "Click on the Product Button", SwingConstants.CENTER);
//adding the labels to the panes
pane.add(headingMainL);
pane.add(selectionL);
//candy button setup
candyB = new JButton("Candy");
//registering the listener for the candy button
candyB.addActionListener(pbHandler);
//chip button setup
chipsB = new JButton("Chips");
//Registering listener for chips button
chipsB.addActionListener(pbHandler);
//gum button setup
gumB = new JButton("Gum");
//registering the listener for the gum button
gumB.addActionListener(pbHandler);
//cookie button setup
cookiesB = new JButton("Cookies");
//registering the listener for the cookie button
cookiesB.addActionListener(pbHandler);
//exit button setup
exitB = new JButton("Exit");
//registering the listener for the exit button
exitB.addActionListener(pbHandler);
pane.add(candyB); //adds the candy button to the pane
pane.add(chipsB); //adds the chips button to the pane
pane.add(gumB); //adds the gum button to the pane
pane.add(cookiesB); //adds the cookies button to the pane
pane.add(exitB); //adds the exit button to the pane
setVisible(true); //show the window and its contents
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//class to handle button events
private class ButtonHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getActionCommand().equals("Exit"))
System.exit(0);
else if (e.getActionCommand().equals("Candy"))
sellProduct(candy, "Candy");
else if (e.getActionCommand().equals("Chips"))
sellProduct(chips, "Chips");
else if (e.getActionCommand().equals("Gum"))
sellProduct(gum, "Gum");
else if (e.getActionCommand().equals("Cookies"))
sellProduct(cookies, "Cookies");
}
}
//Method to sell machine items
private void sellProduct(Dispenser product, String productName) {
//int variables for the amount of money entered, prices, and money needed
int coinsInserted = 0;
int price;
int coinsRequired;
String str;
// if statement for buying the products
if (product.getCount() > 0) {
price = product.getProductCost();
coinsRequired = price - coinsInserted;
while (coinsRequired > 0) {
str = JOptionPane.showInputDialog("To buy " + productName + " please insert " + coinsRequired + " cents");
coinsInserted = coinsInserted
+ Integer.parseInt(str);
coinsRequired = price - coinsInserted;
}
cashRegister.acceptAmount(coinsInserted);
product.makeSale();
JOptionPane.showMessageDialog(null, "Please pick up " + "your " + productName + " and enjoy",
"Thank you, Come again!", JOptionPane.PLAIN_MESSAGE);
} else //if that item is sold out
JOptionPane.showMessageDialog(null, "Sorry " + productName + " is sold out\n" + "Please make another selection",
"Thank you, Come again!", JOptionPane.PLAIN_MESSAGE);
}
public static void main(String[] args) {
candyMachine candyShop = new candyMachine();
}
}
Cash Register Class
public class CashRegister {
private int regiCash; //int variable for storing cash in the "register"
public CashRegister()
{ // default amount of cash on hand is 500
regiCash = 500;
}
//Method that receives the cash entered by the user and updates the register
public void acceptAmount(int amountIn) {
regiCash = regiCash + amountIn;
}
//Constructer for setting the amount of money in the register to a specific amount (500)
public CashRegister(int cashIn)
{
if (cashIn >= 0)
regiCash = cashIn;
else
regiCash = 500;
}
//Method to show the current amount of money in the cash register
public int currentBalance()
{
return regiCash;
}
}
Dispenser Class
public class Dispenser {
private int itemNumber; //int variable for storing the number of items in the dispenser
private int price; //int variable for storing item prices
//item constructor
public Dispenser(int i, int j)
{ //default number of items is 5 and default price is 50
itemNumber = 5;
price = 50;
}
public int getCount()
{
return itemNumber;
}
public void makeSale()
{
itemNumber--;
}
public int getProductCost()
{
return price;
}
}
Button Handler Class
package lab9Final;
public class ButtonHandler {
//Handles the buttons
}

How to add data from another class to JTextField

I have a Gadget, Mobile, MP3 and GadgetShop class. The Gadget is the super class, the Mobile and MP3 are Subclasses of the Superclass and the GadgetShop is the GUI I made.
I just need my GadgetShop to gather the information to place it in the TextFields I've made when I click the button I've made. I have no idea how to pass the information.
I'm using BlueJ by the way.
This is my Mobile Class:
/**Mobile phone class that:
* allows calling credit to be applied that is more than 0
* shows remaining calling credit
* allows a phone number to be added
* shows duration of phone call
*/
public class Mobile extends Gadget
{
private int credit;
private int duration;
private String number = "";
/**
* Constructor for objects of class Mobile.
*/
public Mobile(double ThePrice, int TheWeight, String TheModel, String TheSize)
{
// initialise instance variables
super(ThePrice, TheWeight, TheModel, TheSize);
}
/**
* Insert the duration of the call.
*/
public void insertDuration(int length)
{
System.out.println("A duration of " + length + " minutes for the phone call has been inserted!");
duration = length;
}
/**
* Insert the phone number.
*/
public void insertNumber(String numberAdder)
{
System.out.println("The phone number " + numberAdder + " has been inserted!");
number = numberAdder;
}
/**
* Insert credit for the call.
* A positive amount will need to be added in order for successfull credit to be applied,
* otherwise an error message is displayed.
*/
public void insertCredit(int calls)
{
if(calls > 0) {
System.out.println("Successfully added " + calls + " pounds of credit!");
credit = credit + calls;
}
else {
System.out.println("You need to insert a positive amount more than " + credit + " pounds.");
}
}
/**
* Make the phone call.
* If the credit is equal to or more than the duration, a message displays the phone number and duration of the call.
* If the credit is 0, a message will be displayed to insert more than 0.
* The number of minutes the call lasted is reduced by the amount that was available.
*/
public void makePhoneCall()
{
if(credit == 0)
System.out.println("Insert more than 0 credit to make a phone call!");
else {
if(credit >= duration) {
System.out.println("The phone number " + number + " has been dialed and is being called for " + duration + " minutes");
credit = credit - duration;
duration = 0;
}
else {
if(credit < duration)
System.out.println("You do not have enough credit to make a phone call! Your credit is " + credit + " pounds");
}
}
}
public void mobilePrint()
/**
* Print the details of the mobile.
**/
{
System.out.println("The price of the mobile is " + price + " pounds");
System.out.println("The weight is " + weight + " grams");
System.out.println("The model is " + model);
System.out.println("The size is " + size);
}
}
This is my GadgetShop:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class GadgetShop implements ActionListener
{
private JTextField model, price, weight, size, credit, memory, phoneNo, duration, download, displayNumber;
private JButton addMobile, addMP3, clear, displayAll;
//These JTextField's are for the labels
private JTextField model2, price2, weight2, size2, credit2, memory2, phoneNo2, duration2, download2, displayNumber2;
private JFrame frame;
private ArrayList<Gadget> gadgetDetails;
public GadgetShop()
{
makeFrame();
}
public void addGadget(Gadget newGadget)
{
ArrayList<Gadget> GadgetList = new ArrayList<Gadget>();
Gadget Object = new Gadget(1.00,20,"model","big");
GadgetList.add(Object);
model.setText("hi");
}
public void makeFrame()
{
frame = new JFrame("Gadget Shop");
Container contentPane = frame.getContentPane();
model = new JTextField(10);
price = new JTextField(10);
weight = new JTextField(10);
size = new JTextField(10);
credit = new JTextField(10);
memory = new JTextField(10);
phoneNo = new JTextField(10);
duration = new JTextField(10);
download = new JTextField(10);
displayNumber = new JTextField(10);
//Display Model text box and model info
model2 = new JTextField("Model:");
contentPane.add(model2);
model2.setOpaque(false);
contentPane.add(model);
price2 = new JTextField("Price:");
contentPane.add(price2);
price2.setOpaque(false);
contentPane.add(price);
weight2 = new JTextField("Weight:");
contentPane.add(weight2);
weight2.setOpaque(false);
contentPane.add(weight);
size2 = new JTextField("Size:");
contentPane.add(size2);
size2.setOpaque(false);
contentPane.add(size);
credit2 = new JTextField("Credit:");
contentPane.add(credit2);
credit2.setOpaque(false);
contentPane.add(credit);
memory2 = new JTextField("Memory:");
contentPane.add(memory2);
memory2.setOpaque(false);
contentPane.add(memory);
phoneNo2 = new JTextField("Phone Number:");
contentPane.add(phoneNo2);
phoneNo2.setOpaque(false);
contentPane.add(phoneNo);
duration2 = new JTextField("Duration:");
contentPane.add(duration2);
duration2.setOpaque(false);
contentPane.add(duration);
download2 = new JTextField("Download:");
contentPane.add(download2);
download2.setOpaque(false);
contentPane.add(download);
displayNumber2 = new JTextField("Display Number:");
contentPane.add(displayNumber2);
displayNumber2.setOpaque(false);
contentPane.add(displayNumber);
addMobile = new JButton("Add Mobile Number");
contentPane.add(addMobile);
addMobile.addActionListener(this);
addMP3 = new JButton("Add MP3 Song");
contentPane.add(addMP3);
addMP3.addActionListener(this);
clear = new JButton("Clear");
contentPane.add(clear);
clear.addActionListener(this);
displayAll = new JButton("Display All");
contentPane.add(displayAll);
displayAll.addActionListener(this);
contentPane.setLayout (new GridLayout(4,4));
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (command.equals("Add Mobile Number")) {
addMobile();
}
}
public void addMobile()
{
model.setText("");
}
public void clearText()
{
model.setText("");
price.setText("");
weight.setText("");
size.setText("");
credit.setText("");
memory.setText("");
phoneNo.setText("");
duration.setText("");
download.setText("");
displayNumber.setText("");
}
}
Where I have the:
public void addMobile()
{
model.setText("");
}
I want to add the details of the Mobile Phone
Similarly how you do it in the addGadget method you could add a Mobile parameter to addMobile
public void addMobile(Mobile mobile)
{
// You should add getter methods for attribute
//in the Mobile class to get meaningful values here instead of toString
model.setText(mobile.toString());
}

How to change a Jbutton's function on clicking another Jbutton?

I am writing a program which will convert weight in pounds to kilograms and also weight in Kilograms to pounds. The output window is as follows:
When I want to convert Kilograms to Pounds I click switch button and the output changes as follows:
But the problem is when I click "Convert" it still converts weight to Kilogram instead of Pounds.
I want the "Convert" button's function to change when I click the "Switch" button so it will convert the weight in Kilograms to pounds. Please help.
My source code is as follows:
public class convertApp extends JFrame implements ActionListener {
private JLabel poundlbl = new JLabel("Weight in Pounds");
private JLabel kglbl = new JLabel("Weight in Kilograms");
private JTextField poundbx= new JTextField(12);
private JTextField kgbx= new JTextField(12);
private JButton conbtn=new JButton("Convert");
private JButton switchbtn=new JButton("Switch");
private JButton newconbtn=new JButton("Convert");
private JPanel bxPanel = new JPanel();
public convertApp(){
super("Weight Converter");
bxPanel.setLayout(new GridLayout(5,29,5,5));
bxPanel.add(poundlbl);
bxPanel.add(poundbx);
bxPanel.add(kglbl);
bxPanel.add(kgbx);
bxPanel.add(conbtn);
bxPanel.add(switchbtn);
//bxPanel.setBackground(Color.gray);
this.setLayout(new GridLayout(1,1,0,0));
this.add(bxPanel);
this.setVisible(true);
//what to do if i close
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//put window in the center
this.setLocationRelativeTo(null);
//disable resize
this.setResizable(false);
//pack all the components within the window
this.pack();
conbtn.addActionListener(this);
switchbtn.addActionListener(this);
}
public void actionPerformed(ActionEvent evnt){
if(evnt.getSource()==conbtn){
String poundtext = poundbx.getText();
int pound = Integer.parseInt(poundtext);
double kilo = pound * 0.453592;
kgbx.setText(""+kilo);
}
else if(evnt.getSource()==switchbtn)
{
poundlbl.setText("Weight in Kilograms:");
kglbl.setText("Weight in Pounds:");
if(evnt.getSource()==conbtn){
String kilotext = poundbx.getText();
int kilo = Integer.parseInt(kilotext);
double pound = kilo * 2.20462;
kgbx.setText(""+pound);
}
}
}
}
Create boolean Variable
boolean switch=true;
void kiloGramToPound{
//Convert Codes Here
}
void PoundToKiloGram{
//Convert Codes Here
}
Convert Button actionPerformed
if(switch==true){
kiloGramToPound();
}else{
PoundToKiloGram();
}
Switch Button actionPerformed
if(switch==true){
switch=false;
}else{
switch=true;
}
You cannot change the function itself. You can create a flag that sets true or false (your choice) when you click the 'switch' button. Then check the value of that flag when you click 'convert' and perform the appropriate conversion according to your flag convention.
i.e.
Boolean isPtoK = true;
// [...]
if(isPtoK){
// convert pounds to kilos
} else{
// kilos to pounds
}
I would create a separate function that switches the value of your flag when 'switch' is clicked.
Apologies for not answering your question, but may I suggest you to try KeyListener/KeyAdapter instead of the combination of ActionListeners and buttons.
Example:
textField1.addKeyListener(new ConverterListener(textField2, "2.20462"));
textField2.addKeyListener(new ConverterListener(textField1, "0.453592"));
class ConverterListener extends KeyAdapter {
JTextField destination;
String multiplier;
public ConverterListener(JTextField destination, String multiplier) {
this.destination = destination;
this.multiplier = multiplier;
}
#Override
public void keyReleased(KeyEvent e) {
JTextField source = (JTextField) e.getSource();
String result = convert(source.getText(), multiplier);
destination.setText(result);
}
private String convert(String value, String multiplier) {
String result = "0";
try {
double dblValue = value.isEmpty() ? 0d : Double.parseDouble(value);
double dblMultiplier = value.isEmpty() ? 0d : Double.parseDouble(multiplier);
result = Double.toString(dblValue * dblMultiplier);
} catch (Exception e) {
System.out.println(e);
}
return result;
}
}

Enter button error in java swing

I'm doing a programming exercise.
Miles and kilometer converter.(both case)
However, If I input number and press "Enter", nothing happened.
I don't know what part I need to modify... :(
Help me please..
public class Grid1 extends JFrame{
private JLabel label1,label2;
private JTextField textField1,textField2;
private Container container;
private GridLayout grid1;
// set up GUI
public Grid1(){
super( "Miles to Km / Km to Mile" );
grid1 = new GridLayout( 2, 2 );
container = getContentPane();
container.setLayout( grid1 );
label1 = new JLabel("Mile");
container.add(label1);
textField1 = new JTextField("");
container.add( textField1 );
label2 = new JLabel("Kilometer");
container.add(label2);
textField2 = new JTextField( "" );
container.add( textField2 );
TextFieldHandler handler = new TextFieldHandler();
textField1.addActionListener(handler);
JButton submit = new JButton("Submit");
submit.addActionListener(handler);
setSize(300, 100);
setVisible(true);
}
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
float miles = 0, km = 0;
String string = "";
if(event.getSource() == textField1){
string = "textField1: " + event.getActionCommand();
km = miles * 1.609344f;
}else if(event.getSource() == textField2){
string = "textField2: " + event.getActionCommand();
miles = km / 1.609344f;
}
}
}
public static void main( String args[]){
Grid1 application = new Grid1();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} // end class GridLayoutDemo
You should remove handler from variable textField1 if you need to update data from button click. And in handler class you shold store data into result field/label.
In your case it looks like:
private class TextFieldHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
// In both cases you should get value from textField,
// parse it and store computed values in another field
float miles = 0, km = 0;
try {
if(event.getSource() == textField1){
// Value form field stored in String, you should parse Integer from it
miles = Integer.parseInt(textField1.getText());
km = miles * 1.609344f;
textField2.setText(String.format("%f", km));
}else if(event.getSource() == textField2){
// Value form field stored in String, you should parse Integer from it
km = Integer.parseInt(textField2.getText());
miles = km / 1.609344f;
textField1.setText(String.format("%f", km));
}
} catch(NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Wrong value", "Input error");
}
}
}
Since you are working with a single frame and a single button, I would suggest to set the following line:
frame.getRootPane().setDefaultButton(submitButton);
You can set a default button on each frame you control, the button you set in this method, will automatically listen to enter and invoke your actionPerformed.
You can also use a KeyListener and extend the functionality for your button in this case or in future exercises or projects.
Hope it helps.
All the best... and happy coding :)

JAVA: how to use listeners on JMenuItem and Jbutton to calculate rates

I'm writing a currency converter but I'm having a bit of trouble caculating the exchange rate for each currency. basically I want the user to select a currecy first then enter an amount and press "go" button to calculate the rate. but i'm having trouble with the listeners on JMenuItem and JButton. I've declared two listeners for menuItem and JButton. how do i use the listener on the button to look out for the selection made on the menuIten so that it makes the right currecy calculation?
thanks.
CODE:
private class selectionListener implements ActionListener
{
double EuroToSterling(double euro)
{
double total = Double.parseDouble(amountField.getText());
return total;
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Euros"))
// result = EuroToSterling(10*euro);
currencyMenu.setLabel("Euros");
// answerLabel.setText("this" + EuroToSterling(1.22*2));
if (e.getActionCommand().equals("Japanese Yen"))
currencyMenu.setLabel("Japanese Yen");
}
}
private class GoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
//please help with this section
The usual approach is that the menu listener changes the state of the application (i.e. calls a method that will save the exchange rate in a field).
Then the calculation code can read this value and use it.
Try this out with the Euros. Should give you a place to get started.
/*
*
* Currency converting
*
*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
import javax.swing.UIManager;
public class CurrencyConverterWin extends JFrame {
private JLabel promptLabel;
private JTextField amountField;
private JButton goButton;
private JPanel inputPanel;
private JPanel answerPanel;
private JLabel answerLabel;
private JLabel selectLabel;
private JComboBox currencyMenuBar;
private JPanel menuPanel;
private double result = 0.0;
private double euro = 1.22257;
private double japYen = 152.073;
private double rusRuble = 42.5389;
private double usd = 1.5577;
public CurrencyConverterWin() {
super();
this.setSize(500, 200);
this.setTitle("Currency Converter Window");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(3, 1));
this.selectLabel = new JLabel("Select a currency to convert to: ", JLabel.RIGHT);
this.answerLabel = new JLabel(" ", JLabel.CENTER);
currencyMenuBar = new JComboBox(new String[]{"Euros","Japanese Yen","Russian Rubles","US Dollars"});
this.menuPanel = new JPanel();
this.menuPanel.add(this.selectLabel);
this.menuPanel.add(this.currencyMenuBar);
this.add(this.menuPanel);
this.promptLabel = new JLabel("(select a currency first) ", JLabel.RIGHT);
this.answerLabel = new JLabel(" ", JLabel.CENTER);
this.amountField = new JTextField("", 8);
this.goButton = new JButton("GO");
goButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonClicked(evt);
}
});
this.inputPanel = new JPanel();
this.inputPanel.add(this.promptLabel);
this.inputPanel.add(this.amountField);
this.inputPanel.add(this.goButton);
this.add(this.inputPanel);
this.answerPanel = new JPanel();
this.answerPanel.add(this.answerLabel);
this.add(this.answerPanel);
}
double EuroToSterling() {
double total = Double.parseDouble(amountField.getText()) * euro;
return total;
}
double JapYenToSterling()
{
double japToSterlingTotal = Double.parseDouble(amountField.getText()) * japYen;
return japToSterlingTotal;
}
//String currencyEntered = yearField.getText();
public void buttonClicked(ActionEvent evt) {
if(currencyMenuBar.getSelectedItem().equals("Euros"))
{
answerLabel.setText(EuroToSterling() + " Euros");
}
if(currencyMenuBar.getSelectedItem().equals("Japanese Yen"))
{
answerLabel.setText(JapYenToSterling() + " Japanese Yen");
}
}
public static void main(String[] args) {
try{UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");}
catch (Exception e){e.printStackTrace();}
CurrencyConverterWin win = new CurrencyConverterWin();
win.setVisible(true);
}
}
I would also suggest you use a JComboBox to store the currencies. You would create an object to store both the currency name and the conversion rate. Then when you need to calculate the converted amount you get the selected item from the combo and use its conversion rate in your calculation. With this approach you can easily expand the number of currencies you support.
Check out: How to use Map element as text of a JComboBox for an example to get you start on using an object in the combo box.
I would personally add in an Enumeration to denote the currency conversion type. eg:
public enum ConversionType {
DOLLARS,
EUROS,
RUBLES
//ETC...
}
Using this, you can keep a state variable in the class:
private ConversionType fromType;
This is what you set in your selection listener.
From there it's a matter of doing the different conversions in your action listener based on the state variable (fromType). Something like this:
if( fromType== EUROS ) {
convertEurosToSterling( value1, value2 );
}
This is sort of a general approach - I hope this helps.

Categories