How to add data from another class to JTextField - java

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

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
}

set layout manager in JApplet?

I've created a simple JApplet with three components, but the final added component always overlays the other two so that they are not visible. I believe this is because they are being added to the same area in the default BorderLayout (correct me if I'm wrong!). However, I keep getting an error message when I try to change the LayoutManager. I commented on the line causing the problem below.
import javax.swing.*;
import java.awt.event.*;
public class Vote extends JApplet {
int candidate1 = 50; // this int holds the votes for candidate 1
int candidate2 = 50; // this int holds the votes for candidate 2
public void init() {
JButton vote1 = new JButton("Vote for candidate 1");
JButton vote2 = new JButton("Vote for candidate 2");
JButton results = new JButton("See Results");
vote1.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
++candidate1;
String message = "You voted for candidate 1. \n\nThe current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
vote2.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
++candidate2;
String message = "You voted for candidate 2. \n\nThe current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
results.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String message = "The current results are: \nCandidate 1: " + candidate1 + "\nCandidate 2: " + candidate2;
String title = "Voting results";
JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
}
});
getContentPane().setLayout(new GridLayout(3, 1)); // this line is the one I can't get to work
getContentPane().add(vote1);
getContentPane().add(vote2);
getContentPane().add(results);
}
}

Java actionPerformed method not setting the value for class variable

Please help me with this. I have been stuck for hours!
I have addActionListener to my JTextField, and inside the actionPerformed(), I am trying to modify one class String variable choice. BUT IT IS NOT CHANGING! The value of choice after the actionPerformed() method is always null. I remove the actionListener after it one action has been performed, so I can do some selection later.
The code is below:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package assignment;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.*;
public class GUI_V2 extends JFrame {
//Typing Area;
private JTextField txtEnter = new JTextField();
//Chat area;
private JTextArea txtChat = new JTextArea();
//Scroll
private final JScrollPane scroll = new JScrollPane(txtChat);
private String choice;
public GUI_V2(){
//Frame Attributes
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(2000,2000);
this.setVisible(true);
this.setResizable(false);
this.setLayout(null);
this.setTitle("Menu ChatBot");
//textEnter Attributes
txtEnter.setLocation(20,1825);
txtEnter.setSize(1950,100);
txtEnter.setFont(new Font("Arial",Font.PLAIN,45));
//txtChat Attributes
txtChat.setLocation(22,5);
txtChat.setSize(1950,1800);
txtChat.setFont(new Font("Arial",Font.BOLD,45));
txtChat.setBackground(java.awt.Color.getHSBColor(0.4957f,0.0902f,1.0f));
txtChat.setLineWrap(true);
txtChat.setWrapStyleWord(true);
txtChat.setEditable(false);
//scroll Attributes
scroll.setLocation(22,5);
scroll.setSize(1950,1800);
//Add Items To Frame
this.add(txtEnter);
this.add(scroll);
final String name = greetings();
txtChat.append(botSays("Hi " + name + "! Please enter the mode of operation:"
+ "\n(1) Add keywords and response"
+ "\n(2) Start chatting"
+ "\n(3) Exit the chatbot\n"));
txtEnter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
//add userInput into the txtChat
choice = txtChat.getText();
txtChat.append(name + ": " + choice + "\n");
//auto scroll down
txtChat.setCaretPosition(txtChat.getDocument().getLength());
//set the txtEnter field to be empty
txtEnter.setText("");
txtEnter.removeActionListener(this);
}
});
System.out.println(choice);
//display main menu and ask for user choice
public static void main(String[] args) {
new GUI_V2();
}
private String greetings(){
long currentHour = getCurrentHour();
String time;
if (currentHour < 12)
time = "morning";
else if (currentHour < 18)
time = "afternoon";
else
time = "evening";
txtChat.append(botSays("Good " + time + ", my name is Nova. Welcome to the HOTPOT restaurant!\n"));
pause(1000);
txtChat.append(botSays("First of all, may I know you name? Please.\n"));
pause(1000);
String name = JOptionPane.showInputDialog(null, "Please enter your name:", "My master", JOptionPane.QUESTION_MESSAGE);
return name;
}
public static String botSays(String s){
return "Nova: " + s;
}
public static long getCurrentHour(){
long totalSec = System.currentTimeMillis()/1000;
long totalMin = totalSec / 60;
long totalHour = totalMin / 60;
return (totalHour + 8) % 24; //+8 because SG is GMT+8
}
public static void pause (int millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}
private void displayMenu(String name){
txtChat.append(botSays("Hi " + name + "! Please enter the mode of operation:"
+ "\n(1) Add keywords and response"
+ "\n(2) Start chatting"
+ "\n(3) Exit the chatbot\n"));
txtEnter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
//add userInput into the txtChat
choice = txtChat.getText();
txtChat.append(name + ": " + choice + "\n");
//auto scroll down
txtChat.setCaretPosition(txtChat.getDocument().getLength());
//set the txtEnter field to be empty
txtEnter.setText("");
txtEnter.removeActionListener(this);
}
});
}
}
Your action performed is not working on txtEnter. That is why value of choice is not changing.

Using hashmap to display data in JTextField and update it

Below is code that creates items that have code number name, price and quantity respectively.
public class StockData {
private static class Item {
Item(String n, double p, int q) {
name = n;
price = p;
quantity = q;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
private final String name;
private final double price;
private int quantity;
}
public final static Map<String, Item> stock = new HashMap();
static {
stock.put("00", new Item("Bath towel", 5.50, 10));
stock.put("11", new Item("Plebney light", 20.00, 5));
stock.put("22", new Item("Gorilla suit", 30.00, 7));
stock.put("33", new Item("Whizz games console", 50.00, 8));
stock.put("44", new Item("Oven", 200.00, 4));
}
public static Map<String, Item> getStock() {
return stock;
}
public static String getName(String key) {
Item item = stock.get(key);
if (item == null) {
return null; // null means no such item
} else {
return item.getName();
}
}
public static double getPrice(String key) {
Item item = stock.get(key);
if (item == null) {
return -1.0; // negative price means no such item
} else {
return item.getPrice();
}
}
public static int getQuantity(String key) {
Item item = stock.get(key);
if (item == null) {
return -1; // negative quantity means no such item
} else {
return item.getQuantity();
}
}
public static void update(String key, int extra) {
Item item = stock.get(key);
if (item != null) {
item.quantity += extra;
}
}
}
And here is a different class that is a part of my gui which looks like: http://imgur.com/Jhc4CAz
and my idea is you type the code of an item eg. 22 then type how many you would like to add to the stock so for example 5 you click add so it adds to the variable but immidiately updates the text in the box as you can see on the screen.
I really got myself puzzled with hashmap / list I don't think there is a point copying all the data from hashmap to list and pretty much multiplying it there must be a better way to achieve this.
public class UpdateStock extends JFrame implements ActionListener {
JTextField stockNo = new JTextField(4);
JButton addButton = new JButton("ADD");
JSpinner quantitySlider = new JSpinner();
JTextArea catalog = new JTextArea(7, 30);
List items = new ArrayList();
public UpdateStock(){
setLayout(new BorderLayout());
setBounds(100, 100, 450, 500);
setTitle("Update Stock");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel top = new JPanel();
add("North", top);
JPanel middle = new JPanel();
add("Center", middle);
top.add(stockNo);
top.add(quantitySlider);
top.add(addButton);
catalog.setLineWrap(true);
catalog.setWrapStyleWord(true);
catalog.setEditable(false);
middle.add(new JScrollPane(catalog));
for(String key : StockData.getStock().keySet()) {
catalog.append("Item: " + key +"\n");
items.add(StockData.getName(key));
catalog.append("Name: " + StockData.getName(key) +
" Price: " + StockData.getPrice(key) +
" Qty: " + StockData.getQuantity(key)+"\n");
}
setResizable(false);
setVisible(true);
}
}
your code immediately puts text in the JTextArea because you tell it to. It's right there in the constructor:
for(String key : StockData.getStock().keySet()) {
catalog.append("Item: " + key +"\n");
items.add(StockData.getName(key));
catalog.append("Name: " + StockData.getName(key) +
" Price: " + StockData.getPrice(key) +
" Qty: " + StockData.getQuantity(key)+"\n");
}
If you want to wait until the user picks an item before setting any text, then register an ActionListener on addButton using its addActionListener() method. Use that listener's actionPerformed() method to set the text. Don't forget to remove the code shown above from your constructor, too.
I see you already know about the ActionListener class, since it's implemented by UpdateStock, but it's a little weird (though totally valid!) to do it that way; I don't think I've seen many subclasses of JFrame implement it directly. The usual pattern is to use an anonymous ActionListener and just register that instead. If you really want to use UpdateStock as an ActionListener, then you'll need an actionPerformed() method defined in UpdateStock and you'll need to register this as an action listener on your button.

Calculating the total price

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.

Categories