Calling specific methods between classes - java

Help! I dont know much about java but im trying to create a small program where people can buy items and the stock should update depending on their purchase. I have 2 different classes but what im trying to do is that i want to get the amount of items the user purchases from one class and use that number to update the stock in another class - Here is the section of my code in which i am struggling with
Code for Purchasing Item
public class PurchaseItem extends JFrame implements ActionListener {
JTextField ItemNo = new JTextField(5); //Adds a text field named ItemNo
JTextField AmountNo = new JTextField(5); //Adds a text field named AmountNo
TextArea information = new TextArea(6, 40); //Adds a text area named Information
TextArea reciept = new TextArea (10,50); //Adds a text area named Reciept
JButton Check = new JButton("Check"); //Adds a button named Check
JButton Buy = new JButton("Buy"); //Adds a button named Buy
DecimalFormat pounds = new DecimalFormat("£#,##0.00"); //For output to display in decimal and pounds format
public PurchaseItem() { //PurchaseItem class
this.setLayout(new BorderLayout()); //Adds a new layout for PurchaseItem
JPanel top = new JPanel(); //JPanel is a a container for other components
top.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
JPanel bottom = new JPanel(); //JPanel is a a container for other components
bottom.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
bottom.add(Buy); //Insert the "Buy" JButton on the frame
this.add(bottom, BorderLayout.SOUTH); //Button goes at the bottom of the frame
setBounds(100, 100, 450, 250); //Sets the bounds of the frame
setTitle("Purchase Item"); //Sets the title of the frame
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //Default option to exit frame is through button and not X sign
top.add(new JLabel("Enter Item Key:")); //Add a new JLabel at the top of the frame
top.add(ItemNo); //Set the ItemNo Text Field at the top of the frame
top.add(new JLabel ("Enter Amount:")); //Add a new JLabel at the top of the frame
top.add(AmountNo); //Set the AmountNo Text Field at the top of the frame
top.add(Check); //Set the Check Button at the top of the frame
Buy.setText("Buy"); Buy.setVisible(true); //Makes the text of the Buy Button visible
Check.addActionListener(this); //Add an ActionListener to the Check Button
Buy.addActionListener(this); //Add an ActionListener to the Buy Button
add("North", top);
JPanel middle = new JPanel(); //JPanel is a a container for other components
middle.add(information); //Set the Information Text Area at the middle of the frame
add("Center", middle);
setResizable(false); //Makes the frame not resizeable
setVisible(true); //Makes the frame visible
}
#Override //Overrides the method of the PurchaseItem class to identify mistakes and typos
public void actionPerformed(ActionEvent e) { //actionPerformed class. This is called when the actionListener event happens
String ItemKey = ItemNo.getText(); //String for getting the user input from the ItemNo Text Field
String ItemAmount = AmountNo.getText(); //String for getting the user input from the AmountNo Text Field
String Name = StockData.getName(ItemKey); //String for getting the name of the item from StockData
int Amount = Integer.parseInt(ItemAmount); //Convert String ItemAmount into an Integer variable named Amount
int NewStock = StockData.getQuantity(ItemKey) - Amount; //Integer named NewStock. NewStock is the current stock(from StockData) minus the Amount
double Total = Amount * StockData.getPrice(ItemKey); //Double named Total. Total is the Amount multiplied by the price of the item(from StockData)
Calendar cal = Calendar.getInstance(); //Calendar named cal. getInstance is used to get the current time
SimpleDateFormat Date = new SimpleDateFormat("dd/MM/yyyy"); //SimpleDateFormat named Date. It is used to display the date
SimpleDateFormat Time = new SimpleDateFormat("HH:mm:ss"); //SimpleDateFormat named Time. It is used to display the time
if (Name == null){ //If the Name is invalid and has no return value
information.setText("There is no such item"); //Display the message on the Information Text Area
}
else if (Amount > StockData.getQuantity(ItemKey)) { //Else if the Amount(User Input) is more than the quantity of the item(from StockData)
information.setText("Sorry there is not enough stock available"); //Display the message on the Information Text Area
}
else { //Otherwise
information.setText(Name + " selected: " + Amount); //Add the Name and the Amount of the item on the Information Text Area
information.append("\nIndividual Unit Price: " + pounds.format(StockData.getPrice(ItemKey))); //On a new line add the individual price of the item on the Information Text Area in a pound format(£)
information.append("\nCurrent Stock Available: " + StockData.getQuantity(ItemKey)); //On a new line add the current quantity available according to StockData on the Information Text Area
information.append("\nNew Stock After Sale: " + NewStock); //On a new line add the NewStock on the Information Text Area
information.append("\n\nTotal: " + Amount + " Units" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each"); //On two new lines add the Amount plus the item price(from StockData). This becomes the Total
information.append("\n= " + pounds.format(Total)); //On a new line display the Total in a pounds format(£) on the Information Text Area
}
if (e.getSource() == Buy) { //If the user clicks the Buy Button
int response = JOptionPane.showConfirmDialog(null, "Buy " + Amount + " Units" + " for " + pounds.format(Total) + "?"); //Show a confirm dialog asking the user to confirm the purchase with a Yes, No, or Cancel option
if (response == JOptionPane.YES_OPTION) { //If the user clicks Yes on the confirm dialog
JFrame frame2 = new JFrame(); //Add a new JFrame called frame2
TextArea Reciept = new TextArea ("Receipt For Your Purchase", 20,40); //Add the Receipt Text Area onto frame2 and show the message
Reciept.append("\n\nTime: " + Time.format(cal.getTime())); Reciept.append("\nDate: " + Date.format(cal.getTime())); //On seperate lines add the Time and the Date (from Calendar)
Reciept.append("\n\nYou Have Purchased The Following Item(s): "); //Display the message
Reciept.append("\n\n" + Name + "\n" + Amount + " Units" + "\n" + pounds.format(StockData.getPrice(ItemKey)) + " each"); //On a line add the Name and Item Amount followed by the item price (from StockData) on a new line
Reciept.append("\n\n\n" + Amount + " Unit(s)" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each" + "\nTotal = " + pounds.format(Total)); //After 3 lines display the Item Amount and the item price on the same line. On a new line display the Total in a pounds format
Reciept.append("\n\n\nThank You For Your Purchase" + "\n\nGoodbye :)"); //Show a message on two seperate lines
frame2.pack(); frame2.setSize(375, 380); frame2.setLocation(250, 250); ;frame2.setTitle("Receipt"); //Sets the size, the location, and the title of frame2
frame2.setVisible(true); frame2.setResizable(false); //sets frame2 so that it is visible and not resizable
frame2.add(Reciept); //Display the Reciept Text Area on frame2
frame2.setLayout(new FlowLayout(FlowLayout.CENTER)); //It is set to the center of the frame
}else{ //Otherwise
if (response == JOptionPane.NO_OPTION){ //If the user clicks No or Cancel on the confirm dialog
//Do nothing
}
}
Code for Checking Stock
public class CheckStock extends JFrame implements ActionListener {
JTextField stockNo = new JTextField(7); //adds a text field for user input
JTextField AmountNo = new JTextField(5);
TextArea information = new TextArea(6, 40); //adds a text area for the output
JButton check = new JButton("Check Stock"); //adds a button with the text "Check Stock"
JButton Clear = new JButton();
DecimalFormat pounds = new DecimalFormat("£#,##0.00"); //for output to display in decimal and pound format
public CheckStock() { //"CheckStock" class
setLayout(new BorderLayout()); //adds a new frame for "CheckStock"
setBounds(100, 100, 450, 220); //sets the size and location of the frame
setTitle("Check Stock"); //sets the title of the frame
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //user has to click on "Exit" button instead of X sign
check.addActionListener(this); //adds an action listener for the "check" button so when clicked by user, "actionPerformed" class is called
JPanel top = new JPanel(); //JPanel is a a container for other components. It is used at the top of the frame
add("North", top);
top.add(new JLabel("Enter Item Key:")); //adds a label at the top of tne frame
top.add(stockNo); //adds the "stockNo" text field to the top of the frame
top.add(check); //adds the "check" button to the top of the frame
JPanel middle = new JPanel(); //JPanel is a a container for other components. It is used at the middle of the frame
add("Center", middle);
middle.add(information); //in the middle of the frame, add the "information" text area
setResizable(false); //frame is not resizable
setVisible(true); //frame is visible
}
public void actionPerformed(ActionEvent e) { //this code is fired once the user runs the ActionListener
String key = stockNo.getText(); //string named "key" for the stockNo
String name = StockData.getName(key); //string named "name" for the stockData
int Quantity = StockData.getQuantity(key);
int NewStock;
if (name == null) { //if there is no input in the text field
information.setText("Enter Item Key"); //display the message on the text area
}
else if (e.getSource() == check) {
StockData.getQuantity(key);
information.append( "" + StockData.getName(key));
information.append("\n New Stock: " + StockData.getQuantity(key)); //otherwise
information.setText(name); //display the name of the item
information.append("\nPrice: " + pounds.format(StockData.getPrice(key))); //display the price of the item using pound format
information.append("\nPrevious Stock: " + Quantity); //display the amount in stock for the item according to StockData
}
}
}

You didn't initialise the object Update: your line of code should be
PurchaseItem Update = new PurchaseItem();
(As another point I can't see any code that adds the JComponent you created (e.g. the buttons, the text fields,...) to the two frames of the respective classes or that displays the two frames; if it isn't included in your code be sure to add these pieces of code).
Finally, if you need a code that checks for changes in the value of Updated, here's the simplest (but not the only) technique you can use, creating a thread (see the Oracle documentation to know what are threads and how to use them):
int refreshTime = 1000; // Refresh time in milliseconds
boolean running = true; // Set it to false if you want to stop the thread
Runnable r = new Runnable({
#Override
public void run() {
while(running) {
Thread.sleep(refreshTime);
// Put here your code to update your frames or your variables
}
});

Related

how to combine joptionpane with combobox

i want my joptionpane can combine with combobox,and the combobox data is in database, how i managed that.
i've tried change but the red code always show
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String wel = sdf.format(cal1.getDate());
String NamaFile = "/report/harianMasuk.jasper";
HashMap hash = new HashMap();
String tak = JOptionPane.showOptionDialog(null,id.getSelectedIndex()-1,"Laporan Supplier",JOptionPane.QUESTION_MESSAGE);
try {
hash.put("til", wel);
hash.put("rul", tak);
runReportDefault(NamaFile, hash);
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
Read the section from the Swing tutorial on Getting User Input From a Dialog.
It demonstrates how to display a combo box in a JOptionPane.
Not exactly sure what you are trying to accomplish but it appears to be that you want to utilize a JComboBox within a JOptionPane dialog window. This ComboBox would be filled with specific data from your database. The User is to select from this ComboBox and your application continues processing based on that selection. If this is the case then you might want to try something like this:
String selectedItem = "";
int selectedItemIndex = -1;
/* Ensure dialog never hides behind anything (use if
the keyword 'this' can not be used or there is no
object to reference as parent for the dialog). */
JFrame iframe = new JFrame();
iframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iframe.setAlwaysOnTop(true);
// ---------------------------------------------------
int btns = JOptionPane.OK_CANCEL_OPTION;
String dialogMessage = "<html>Select the desired item from the Drop-Down "
+ "list<br>you want to work with:<br><br></html>";
String dialogTitle = "Your Fav Items";
/* Up to you to gather what you want placed into the
JComboBox that will be displayed within the JOptionPane. */
String[] comboBoxItems = {"Your", "DB", "Items", "You", "Want", "To",
"Add", "To", "ComboBox"};
BorderLayout layout = new BorderLayout();
JPanel topPanel = new JPanel(layout);
JLabel label = new JLabel(dialogMessage);
topPanel.add(label, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
JComboBox cb = new JComboBox();
cb.setModel(new DefaultComboBoxModel<>(comboBoxItems));
cb.setSelectedIndex(-1);
centerPanel.add(cb, BorderLayout.CENTER);
topPanel.add(centerPanel);
// Ensure a selection or Cancel (or dialog close)
while (selectedItemIndex < 0) {
int res = JOptionPane.showConfirmDialog(iframe, topPanel, dialogTitle, btns);
if (res == 2) {
selectedItem = "Selection Option Was Canceled!";
break;
}
selectedItemIndex = cb.getSelectedIndex();
if (res == JOptionPane.OK_OPTION) {
if (selectedItemIndex == -1) {
JOptionPane.showMessageDialog(iframe, "<html>You <b>must</b> "
+ "select something or select <font color=red><b>Cancel</b></font>.",
"Invalid Selection...", JOptionPane.WARNING_MESSAGE);
}
else {
selectedItem = cb.getSelectedItem().toString();
}
}
iframe.dispose();
}
JOptionPane.showMessageDialog(iframe, "<html>You selected the ComboBox item:"
+ "<br><br><b><font color=blue><center>" + selectedItem + "</center>"
+ "</font></b><br></html>", "Selected Item", JOptionPane.INFORMATION_MESSAGE);
iframe.dispose();
With the above code, the Input dialog that will be displayed would look something like this:
It is up to you to find the means to fill the comboBoxItems String Array used within the code above.

JTextArea displaying weird error message

I have checked all over internet looking for what may be causing this error... but I haven't been lucky. My code basically gets the text from a JTextField and a JComboBox and passes it to a JTextArea when the user presses a button. That's the code...
final JTextField quant = new JTextField(3);
final JTextArea list = new JTextArea(10,30);
list.setEditable(false);
JPanel entry = new JPanel();
entry.add(quant);
entry.add(optionProds);
JButton adiciona = new JButton("Adicionar");
entry.add(adiciona);
entry.add(list);
adiciona.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
list.setText(optionProds.getSelectedItem().toString() + "-" + quant);
System.out.print(list.getText());
}
});
finalAction.add(entry);
The problem is that when I press the button, the JTextArea won't display the name of the product and its amount, but the text below instead:
Gato-javax.swing.JTextField[,134,8,37x20,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#2034094f,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=3,columnWidth=11,command=,horizontalAlignment=LEADING]
What could be causing this?
use
list.setText(optionProds.getSelectedItem().toString() + "-" + quant.getText());
instead of
list.setText(optionProds.getSelectedItem().toString() + "-" + quant);
why do you print quant? quant is a jtextfiled .that's not a error .this is what you get when you print a jcomponent .when you print a jcomponent you get properties and values such as location,border,margin...etc. so you should print the text using getText() method

Trying to Display text input in a java a JFrame window [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm using JCreator Pro. I'm trying to get information entered in the textfields to display and calculate the selling price of used cars. The window looks like this:
When I click display, I want the information to appear on the bottom half of the window (car make and model, year of manufacturing, sale price)
But when I do click it, all I get are these lines of text in the General output window and I can't make out what's wrong. My code compiles without any errors.
Here's my main class for reference:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MIT141674CarDetailsTest extends JFrame implements ActionListener {
MIT141674Car car;
JTextField jtfMakeModel, jtfYear, jtfPurchPrice;
JButton jbtnDisplay, jbtnClear;
JLabel jlblMakeModel, jlblYear, jlblSellPrice;
public MIT141674CarDetailsTest() {
setSize(500, 210);
setLocationRelativeTo(null);
setTitle("Purchased car details");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(7, 2));
// input
add(new JLabel(" Enter car make and model: "));
jtfMakeModel = new JTextField();
add(jtfMakeModel);
add(new JLabel(" Enter year of manufacturing: "));
jtfYear = new JTextField();
add(jtfYear);
add(new JLabel(" Enter purchase price: "));
jtfPurchPrice = new JTextField();
add(jtfPurchPrice);
// buttons
jbtnDisplay = new JButton("Display");
add(jbtnDisplay);
jbtnDisplay.addActionListener(this);
jbtnClear = new JButton("Clear all");
add(jbtnClear);
jbtnClear.addActionListener(this);
// display car
add(new JLabel(" Car make and model: "));
jlblMakeModel = new JLabel("");
add(jlblMakeModel);
add(new JLabel(" Year of manufacturing: "));
jlblYear = new JLabel("0000");
add(jlblYear);
add(new JLabel(" Sale price: "));
jlblSellPrice = new JLabel("$0.00");
add(jlblSellPrice);
}
public static void main(String[] args) {
MIT141674CarDetailsTest carWin = new MIT141674CarDetailsTest();
carWin.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("Display")) {
int carYear = Integer.parseInt(jtfYear.getText());
if (carYear >= 2009) {
double pPrice = Double.parseDouble(jtfPurchPrice.getText());
if (pPrice > 0) {
car = new MIT141674Car(jtfMakeModel.getText(),
carYear, pPrice);
jlblMakeModel.setText(car.getMakeModel());
jlblYear.setText(Integer.toString(car.getYear()));
jlblSellPrice
.setText(Double.toString(car.getSellingPrice()));
} else
// pPrice <=0 - invalid
JOptionPane.showMessageDialog(null,
"Invalid purchase price, please re-enter");
} // carYear <=2009
else
// invalid carYear
JOptionPane.showMessageDialog(null,
"Invalid year of manufacturing, please re-enter");
} // if display
else
// not Display button, then check if it's Clear all button
if (str.equals("Clear all")) {
// remove text from all text fields
jtfMakeModel.setText("");
jtfYear.setText("");
jtfPurchPrice.setText("");
// clear labels
jlblMakeModel.setText("");
jlblYear.setText("0000");
jlblSellPrice.setText("$0.00");
}
} // actionPerformed
} // end of class
Can anyone help me and tell me what is wrong?
EDIT: I have partially solved my problem by doing what #Exbury mentioned by changing
car = new MIT141674Car (jtfMakeModel.getText(), car.getYear(), car.getSellingPrice());
to
car = new MIT141674Car (jtfMakeModel.getText(), carYear, pPrice);
But now I've found that the year entered only displays if I enter 2009, any other years entered after 2009 comes up as 0.
Giving one class a getter/accessor method that extracts the desired information of JTextField and giving the other class a setter/mutator method that allows outside objects to inject the desired information, here to set the text of its JLabel
While creating car object you are using same car reference (null) in constructor
Change this to
car = new MIT141674Car (jtfMakeModel.getText(), car.getYear(), car.getSellingPrice());`
to
car = new MIT141674Car (jtfMakeModel.getText(), carYear, pPrice);

Writing actionListner to display form input on console upon confirmation

I am currently constructing a GUI which allows me to add new cruises to the system. I want to write an actionListner which once the user clicks on "ok" then the form input will be displayed as output on the console.
I currently have the following draft to complete this task:
ok = new JButton("Add Cruise");
ok.setToolTipText("To add the Cruise to the system");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
int selected = typeList2.getSelectedIndex();
String tText = typeList2[selected];
Boolean addtheCruise = false;
addtheCruise = fleet.addCruise();
fleet.printCruise();
if (addtheCruise)
{
frame.setVisible(false);
}
else
{ // Report error, and allow form to be re-used
JOptionPane.showMessageDialog(frame,
"That Cruise already exists!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
buttonPanel.add(ok);
Here is the rest of the code to the Form input frame:
contentPane2 = new JPanel (new GridLayout(18, 1)); //row, col
nameInput = new JLabel ("Input Cruise Name:");
nameInput.setForeground(normalText);
contentPane2.add(nameInput);
Frame2.add(contentPane2);
Cruisename = new JTextField("",10);
contentPane2.add(Cruisename);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
confirmPanel = new JPanel ();
confirmPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
confirmPanel.setBorder(BorderFactory.createLineBorder(Color.PINK));
addItinerary = new JButton("Add Itinerary");
confirmPanel.add(Add);
confirmPanel.add(addItinerary );
Frame2.add(confirmPanel, BorderLayout.PAGE_END);
Frame2.setVisible(true);
contentPane2.add(Cruisename);
Frame2.add(contentPane2);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
contentPane2.setBorder(BorderFactory.createLineBorder(Color.black));
//Label for start and end location jcombobox
CruiseMessage = new JLabel ("Enter Start and End Location of new Cruise:");
CruiseMessage.setForeground(normalText);
contentPane2.add(CruiseMessage);
Frame2.add(contentPane2);
/**
* creating start location JComboBox
*/
startL = new JComboBox();
final JComboBox typeList2;
final String[] typeStrings2 = {
"Select Start Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
startL = new JComboBox(typeStrings2);
contentPane2.add(startL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
/**
* creating end location JComboBox
*/
endL = new JComboBox();
final JComboBox typeList3;
final String[] typeStrings3 = {
"Select End Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
endL = new JComboBox(typeStrings3);
contentPane2.add(endL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
//Label for select ship jcombobox
selectShipM = new JLabel ("Select Ship to assign Cruise:");
selectShipM.setForeground(normalText);
contentPane2.add(selectShipM);
Frame2.add(contentPane2);
/**
* creating select ship JCombobox
* select ship to assign cruise
*/
selectShip = new JComboBox();
final JComboBox typeList4;
final String[] typeStrings4 = {
"Select Ship", "Dalton Princess", "Stafford Princess" };
selectShip = new JComboBox(typeStrings4);
contentPane2.add(selectShip);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
I need all form inputs from the code above to be displayed on the console upon completion.
Summary:
1. I have two ships in one fleet
2. To add new cruise, all fields (Name, start date, end date, ship) must be selected.
The Problem:
1. I keep coming up with errors when creating " fleet = new Fleet();" in my constructor. Even though I have declared it in my class.
2. In the draft code below, line 5 states "typeList2", however, I have two JComboBox's - two different type Strings for both drop down menu's (Shown in the rest of the code). How do I input both typeLists to the output rather than just one?
Thank you.

creating a working Java GUI

I'm a Java newbie. I am in a college intro Java course, and I'm at a point now where none of my programs are working.
This point is at the GUI creation chapter. I'm not sure what I'm doing wrong. I've been working on this non-stop for over a week and no progress. I've searched far and wide across the Java forums, YouTube videos, previous StackOverflow questions, Oracle demos and tutorials; I updated my Java JDK to 1.7 just in case, and nothing has worked.
First I should mention that I was previously having a problem where it would say "javaw.exe has encountered a problem and needs to close," but this proglem seems to have disappeared after updating to 1.7 I'm okay on that. I am running the program in the IDE Eclipse helios.
I decided to try and change the program to a JApplet to see if this would help, but it hasn't. I tried debugging but it won't even let me finish debugging. What am I doing wrong? When I run the JApplet, I get ouput on the console, but StackOverflow won't let me post it.
Here is a copy of my code. The javadocs aren't finished, and I apologize for this. I have just made so many changes trying to fix things that I haven't been able to keep up at the pace of creating all the javadocs. I should also warn you that I did create an input format validation (do-while try-catch), but I have omitted this here because first I'm trying to figure out what I'm doing wrong before moving on to adding this. I also apologize for the sloppy indentations in the code. somehow it didn't transfer very well on to the StackOverflow website.
package assignment12;
/*
* File: CalculateBill.java
* ------------------------
* This program calculates a table's bill at a restaurant.
* The program uses a frame user interface with the following components:
* input textfields for the waiter name and table number
* four interactive combo boxes for each category of the menu containing all the menu items
* a listbox that keeps track of menu item that is ordered
* buttons that allow the user to delete an item or clear all the items on the listbox
* a textarea that displays the table and waiter name entered
* a label that refreshes the total, subtotal, and tax when an item is entered or deleted
* a restaurant logo for "Charlotte's Apple tree restaurant"
*/
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* CalculateBill.java uses these additional files:
* images/appletree.gif
*/
/**
*
* #version 1.7
* #since 2011-11-21
*/
#SuppressWarnings("serial")
public class CalculateBill extends JPanel implements ActionListener {
JComboBox beverageList;
JComboBox appetizerList;
JComboBox dessertList;
JComboBox maincourseList;
JLabel restaurantLogo;
JTextField textTableNum; //where the table number is entered
JTextField waiterName; //where the waiter name is entered
JTextArea textArea;//where the waiter name and table number appears at the bottem
JLabel waiter;
JLabel table;
DefaultListModel model;//model
JList list; // list
static int tableNum = 0; // setting table number to an integer outside the range (1-10) keeps loop going until
// valid user entry in textTableNum textfield
String tn; //string value of table number
String wn; //string value of waiter name
JScrollPane scrollpane;
public double subtotal = 0.00;
public double tax = 0.00;
public double total = 0.00;
JLabel totallabel;
CalculateBill() {
super(new BorderLayout());
//create and set up the window.
JFrame frame = new JFrame("Charlotte's Appletree Restaurant");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 600));
String[] beverages = {"Beverages", "Soda", "Tea", "Coffee", "Mineral Water", "Juice", "Milk"};
String[] appetizers = {"Appetizers", "Buffalo Wings", "Buffalo Fingers", "Potato Skins", "Nachos", "Mushroom Caps", "Shrimp Cocktail", "Chips and Salsa"};
String[] maincourses = {"Main Courses", "Seafood Alfredo", "Chicken Alfredo", "Chicken Picatta", "Turkey Club", "Lobster Pie", "Prime Rib", "Shrimp Scampi", "Turkey Dinner", "Stuffed Chicken"};
String[] desserts = {"Desserts", "Apple Pie", "Sundae", "Carrot Cake", "Mud Pie", "Apple Crisp"};
/*create the combo boxes, selecting the first item at index 0.
indices start at 0, so so 0 is the name of the combo box*/
// beverages combobox
beverageList = new JComboBox(beverages);
beverageList.setEditable(false);
beverageList.setSelectedIndex(0);
add(new JLabel(" Beverages:"), BorderLayout.CENTER);
add(beverageList, BorderLayout.CENTER);
// appetizers combobox
appetizerList = new JComboBox(appetizers);
appetizerList.setEditable(false);
appetizerList.setSelectedIndex(0);
add(new JLabel(" Appetizers:"), BorderLayout.CENTER);
add(appetizerList, BorderLayout.CENTER);
// maincourses combobox
maincourseList = new JComboBox(maincourses);
maincourseList.setEditable(false);
maincourseList.setSelectedIndex(0);
add(new JLabel(" Main courses:"), BorderLayout.CENTER);
add(maincourseList, BorderLayout.CENTER);
// desserts combox
dessertList = new JComboBox(desserts);
dessertList.setEditable(false);
dessertList.setSelectedIndex(0);
add(new JLabel(" Desserts:"), BorderLayout.CENTER);
add(dessertList, BorderLayout.CENTER);
// listbox
model = new DefaultListModel();
JPanel listPanel = new JPanel();
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
// list box continued
JScrollPane listPane = new JScrollPane();
listPane.getViewport().add(list);
listPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
listPanel.add(listPane);
// total label
totallabel = new JLabel(setTotalLabelAmount());
add((totallabel), BorderLayout.SOUTH);
totallabel.setVisible(false);
// sets up listbox buttons
add(new JButton("Delete"), BorderLayout.SOUTH);
add(new JButton("Clear All"), BorderLayout.SOUTH);
// sets up restaurant logo
restaurantLogo = new JLabel();
restaurantLogo.setFont(restaurantLogo.getFont().deriveFont(Font.ITALIC));
restaurantLogo.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
restaurantLogo.setPreferredSize(new Dimension(123, 200 + 10));
ImageIcon icon = createImageIcon("images/appletree.gif");
restaurantLogo.setIcon(icon);
restaurantLogo.setText("Charlotte's Apple Tree Restaurant");
add((restaurantLogo), BorderLayout.NORTH);
// sets up the label next to textfield for table number
table = new JLabel(" Enter Table Number (1-10):");
/**
* #throws InputMismatchException if the textfield entry is not an integer
*
*/
// sets up textfield next to table lable
table.setLabelFor(textTableNum);
add((table), BorderLayout.NORTH);
// sets up label for waiter name
waiter = new JLabel(" Enter Waiter Name: ");
// sets up textfield next to waiter lable
waiter.setLabelFor(waiterName);
add((waiter), BorderLayout.NORTH);
// listens to the textfields
textTableNum.addActionListener(this);
waiterName.addActionListener(this);
// sets up textarea
textArea = new JTextArea(5, 10);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
// lays out listpanel
listPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(listPane, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
scrollPane.setVisible(true);
}
private double getPrices(String item) {
// create hashmap to store menu items with their corresponding prices
HashMap<String, Double> hm = new HashMap<String, Double>();
// put elements to the map
hm.put("Soda", new Double(1.95));
hm.put("Tea", new Double(1.50));
hm.put("Coffee", new Double(1.25));
hm.put("Mineral Water", new Double(2.95));
hm.put("Juice", new Double(2.50));
hm.put("Milk", new Double(1.50));
hm.put("Buffalo Wings", new Double(5.95));
hm.put("Buffalo Fingers", new Double(6.95));
hm.put("Potato Skins", new Double(8.95));
hm.put("Nachos", new Double(8.95));
hm.put("Mushroom Caps", new Double(10.95));
hm.put("Shrimp Cocktail", new Double(12.95));
hm.put("Chips and Salsa", new Double(6.95));
hm.put("Seafood Alfredo", new Double(15.95));
hm.put("Chicken Alfredo", new Double(13.95));
hm.put("Chicken Picatta", new Double(13.95));
hm.put("Turkey Club", new Double(11.95));
hm.put("Lobster Pie", new Double(19.95));
hm.put("Prime Rib", new Double(20.95));
hm.put("Shrimp Scampi", new Double(18.95));
hm.put("Turkey Dinner", new Double(13.95));
hm.put("Stuffed Chicken", new Double(14.95));
hm.put("Apple Pie", new Double(5.95));
hm.put("Sundae", new Double(3.95));
hm.put("Carrot Cake", new Double(5.95));
hm.put("Mud Pie", new Double(4.95));
hm.put("Apple Crisp", new Double(5.95));
double price = hm.get(item);
return price;
}
/**
* validates that the correct path for the image was found to prevent crash
*
* #param path is the icon path of the restaurant logo
*
* #return nothing if you can't find the image file
*
* #return imageIcon(imgURL) the path to image if you can find it
*/
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = CalculateBill.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
JOptionPane.showMessageDialog(null, "Couldn't find file: "
+ path, "image path error", JOptionPane.ERROR_MESSAGE);
return null;
}
}
//Listens to the combo boxes
private void getSelectedMenuItem(JComboBox cb) {
String mnItem = (String) cb.getSelectedItem();
updateListBox(mnItem);
}
/**
* updates the list box
*
* #param name the element to be added to the list box
*/
private void updateListBox(String name) {
totallabel.setVisible(false);
model.addElement(name);
Addition(getPrices(name));
totallabel.setVisible(true);
}
void showWaiterAndTableNum() {
textArea.append("Table Number: " + tn + " Waiter: " + wn);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* adds to the subtotal/total calculator.
*
* #param s The name of the menu item which will be used to access its hashmap key value.
*
*/
private void Addition(double addedP) {
subtotal = subtotal + addedP;
tax = .0625 * subtotal;
total = subtotal + tax;
}
/**
* subtracts from to the subtotal/total calculator.
*
* #param subtractedp The price of the menu item which will be used to access its hashmap key value.
*
*/
// sets up the 'total' label which shows subtotal, tax, total
private void Subtraction(double subtractedp) {
subtotal = subtotal - subtractedp;
tax = subtotal * .0625;
total = subtotal + tax;
}
private void resetCalculator() {
subtotal = 0.00;
tax = 0.00;
total = 0.00;
}
// listens to list buttons
#Override
public void actionPerformed(ActionEvent e) {
JTextField tf = (JTextField) e.getSource();
if (tf.equals("textTableNum")) {
tn = tf.getText();
} else if (tf.equals("waiterName")) {
wn = tf.getText();
}
String cmd = e.getActionCommand();
if (cmd.equals("Delete")) {
totallabel.setVisible(false);
ListSelectionModel selmodel = list.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
String foodName = (String) list.getSelectedValue();
Subtraction(getPrices(foodName));
totallabel.setVisible(true);
//subtracts from the subtotal
if (index >= 0) {
model.remove(index);
}
} else if (cmd.equals("Clear all")) {
model.clear();
resetCalculator();
}
}
//combobox mouse listener
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JComboBox cb = (JComboBox) e.getSource();
getSelectedMenuItem(cb);
}
}
private String setTotalLabelAmount() {
String totlab = "Subtotal: $ " + subtotal + " Tax: $" + tax + "\n" + "Total: $ " + total;
return totlab;
}
}
**my applet:**
package assignment12;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class Main extends JApplet {
/**
* #param args
*/
public void init() {
// schedule job for event-dispatching
//while showing Aplication GUI
try {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} catch (Exception e) {
System.err.println("createAndShowGUI didn't complete successfully");
}
}
// create and show GuI
private void createAndShowGUI() {
//Create and set up the content pane.
CalculateBill newContentPane = new CalculateBill();
newContentPane.setOpaque(true); //content panes must be opaque
setContentPane(newContentPane);
}
}
Well, on the one hand "what isn't wrong" comes to mind, but in truth you've come quite away.
There are several issues going on here. I've only taken a stab at some of them.
It would be easier to subclass JPanel than JFrame. Create a panel, and add it to a frame. See Eric's answer on how to structure that, and see the main method below.
You have two missing JTextFields: textTableNum, and waiterName. First thing I got build this up is an NPE at these two locations. Next, your constraints are wrong for the GridBag. I am not a GridBag person. GridBag gives me hives, so I can't say what's wrong with those, so I eliminated the constraints and replaced them with 'null'. Once I did this, I at least got a frame and a GUI.
Next, all of your BorderLayout code is wrong. When you specify a location on a Border Layout, that's exactly what you are doing -- specifying a location. If you put 3 things in BorderLayout.NORTH, they will all go up there, and layer on top of each other (that it you will see only one of them). So, clearly, all of your layout code needs a lot of work.
After some butchery, we have this:
package soapp;
/*
* File: CalculateBill.java
* ------------------------
* This program calculates a table's bill at a restaurant.
* The program uses a frame user interface with the following components:
* input textfields for the waiter name and table number
* four interactive combo boxes for each category of the menu containing all the menu items
* a listbox that keeps track of menu item that is ordered
* buttons that allow the user to delete an item or clear all the items on the listbox
* a textarea that displays the table and waiter name entered
* a label that refreshes the total, subtotal, and tax when an item is entered or deleted
* a restaurant logo for "Charlotte's Apple tree restaurant"
*/
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* CalculateBill.java uses these additional files:
* images/appletree.gif
*/
/**
*
* #version 1.7
* #since 2011-11-21
*/
#SuppressWarnings("serial")
public class CalculateBill extends JPanel implements ActionListener {
JComboBox beverageList;
JComboBox appetizerList;
JComboBox dessertList;
JComboBox maincourseList;
JLabel restaurantLogo;
JTextField textTableNum; //where the table number is entered
JTextField waiterName; //where the waiter name is entered
JTextArea textArea;//where the waiter name and table number appears at the bottem
JLabel waiter;
JLabel table;
DefaultListModel model;//model
JList list; // list
static int tableNum = 0; // setting table number to an integer outside the range (1-10) keeps loop going until
// valid user entry in textTableNum textfield
String tn; //string value of table number
String wn; //string value of waiter name
JScrollPane scrollpane;
public double subtotal = 0.00;
public double tax = 0.00;
public double total = 0.00;
JLabel totallabel;
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame("SO App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CalculateBill cb = new CalculateBill();
frame.getContentPane().add(cb);
frame.pack();
frame.setVisible(true);
}
CalculateBill() {
super(new BorderLayout());
JPanel panel;
//create and set up the window.
// JFrame frame = new JFrame("Charlotte's Appletree Restaurant");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setPreferredSize(new Dimension(300, 600));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
String[] beverages = {"Beverages", "Soda", "Tea", "Coffee", "Mineral Water", "Juice", "Milk"};
String[] appetizers = {"Appetizers", "Buffalo Wings", "Buffalo Fingers", "Potato Skins", "Nachos", "Mushroom Caps", "Shrimp Cocktail", "Chips and Salsa"};
String[] maincourses = {"Main Courses", "Seafood Alfredo", "Chicken Alfredo", "Chicken Picatta", "Turkey Club", "Lobster Pie", "Prime Rib", "Shrimp Scampi", "Turkey Dinner", "Stuffed Chicken"};
String[] desserts = {"Desserts", "Apple Pie", "Sundae", "Carrot Cake", "Mud Pie", "Apple Crisp"};
/*create the combo boxes, selecting the first item at index 0.
indices start at 0, so so 0 is the name of the combo box*/
// beverages combobox
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
beverageList = new JComboBox(beverages);
beverageList.setEditable(false);
beverageList.setSelectedIndex(0);
panel.add(new JLabel(" Beverages:"), BorderLayout.CENTER);
panel.add(beverageList, BorderLayout.CENTER);
add(panel);
// appetizers combobox
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
appetizerList = new JComboBox(appetizers);
appetizerList.setEditable(false);
appetizerList.setSelectedIndex(0);
panel.add(new JLabel(" Appetizers:"), BorderLayout.CENTER);
panel.add(appetizerList, BorderLayout.CENTER);
// maincourses combobox
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
maincourseList = new JComboBox(maincourses);
maincourseList.setEditable(false);
maincourseList.setSelectedIndex(0);
panel.add(new JLabel(" Main courses:"), BorderLayout.CENTER);
panel.add(maincourseList, BorderLayout.CENTER);
add(panel);
// desserts combox
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
dessertList = new JComboBox(desserts);
dessertList.setEditable(false);
dessertList.setSelectedIndex(0);
panel.add(new JLabel(" Desserts:"), BorderLayout.CENTER);
panel.add(dessertList, BorderLayout.CENTER);
add(panel);
// listbox
model = new DefaultListModel();
JPanel listPanel = new JPanel();
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
// list box continued
JScrollPane listPane = new JScrollPane();
listPane.getViewport().add(list);
listPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
listPanel.add(listPane);
add(listPanel);
// total label
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
totallabel = new JLabel(setTotalLabelAmount());
panel.add((totallabel), BorderLayout.SOUTH);
totallabel.setVisible(false);
add(panel);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
// sets up listbox buttons
panel.add(new JButton("Delete"), BorderLayout.SOUTH);
panel.add(new JButton("Clear All"), BorderLayout.SOUTH);
add(panel);
// sets up restaurant logo
// restaurantLogo = new JLabel();
// restaurantLogo.setFont(restaurantLogo.getFont().deriveFont(Font.ITALIC));
// restaurantLogo.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
// restaurantLogo.setPreferredSize(new Dimension(123, 200 + 10));
// ImageIcon icon = createImageIcon("images/appletree.gif");
// restaurantLogo.setIcon(icon);
// restaurantLogo.setText("Charlotte's Apple Tree Restaurant");
// add((restaurantLogo), BorderLayout.NORTH);
// sets up the label next to textfield for table number
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
table = new JLabel(" Enter Table Number (1-10):");
/**
* #throws InputMismatchException if the textfield entry is not an integer
*
*/
// sets up textfield next to table lable
textTableNum = new JTextField();
table.setLabelFor(textTableNum);
panel.add((table), BorderLayout.NORTH);
panel.add(textTableNum, BorderLayout.NORTH);
add(panel);
// sets up label for waiter name
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
waiter = new JLabel(" Enter Waiter Name: ");
waiterName = new JTextField();
// sets up textfield next to waiter lable
waiter.setLabelFor(waiterName);
panel.add((waiter), BorderLayout.NORTH);
panel.add(waiterName, BorderLayout.NORTH);
add(panel);
// listens to the textfields
textTableNum.addActionListener(this);
waiterName.addActionListener(this);
// sets up textarea
textArea = new JTextArea(5, 10);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
// lays out listpanel
// listPanel.setLayout(new GridBagLayout());
// GridBagConstraints c = new GridBagConstraints();
// c.gridwidth = GridBagConstraints.REMAINDER;
// c.fill = GridBagConstraints.HORIZONTAL;
// add(listPane, c);
// add(listPane, null);
// c.fill = GridBagConstraints.BOTH;
// c.weightx = 1.0;
// c.weighty = 1.0;
// add(scrollPane, c);
add(scrollPane, null);
scrollPane.setVisible(true);
}
private double getPrices(String item) {
// create hashmap to store menu items with their corresponding prices
HashMap<String, Double> hm = new HashMap<String, Double>();
// put elements to the map
hm.put("Soda", new Double(1.95));
hm.put("Tea", new Double(1.50));
hm.put("Coffee", new Double(1.25));
hm.put("Mineral Water", new Double(2.95));
hm.put("Juice", new Double(2.50));
hm.put("Milk", new Double(1.50));
hm.put("Buffalo Wings", new Double(5.95));
hm.put("Buffalo Fingers", new Double(6.95));
hm.put("Potato Skins", new Double(8.95));
hm.put("Nachos", new Double(8.95));
hm.put("Mushroom Caps", new Double(10.95));
hm.put("Shrimp Cocktail", new Double(12.95));
hm.put("Chips and Salsa", new Double(6.95));
hm.put("Seafood Alfredo", new Double(15.95));
hm.put("Chicken Alfredo", new Double(13.95));
hm.put("Chicken Picatta", new Double(13.95));
hm.put("Turkey Club", new Double(11.95));
hm.put("Lobster Pie", new Double(19.95));
hm.put("Prime Rib", new Double(20.95));
hm.put("Shrimp Scampi", new Double(18.95));
hm.put("Turkey Dinner", new Double(13.95));
hm.put("Stuffed Chicken", new Double(14.95));
hm.put("Apple Pie", new Double(5.95));
hm.put("Sundae", new Double(3.95));
hm.put("Carrot Cake", new Double(5.95));
hm.put("Mud Pie", new Double(4.95));
hm.put("Apple Crisp", new Double(5.95));
double price = hm.get(item);
return price;
}
/**
* validates that the correct path for the image was found to prevent crash
*
* #param path is the icon path of the restaurant logo
*
* #return nothing if you can't find the image file
*
* #return imageIcon(imgURL) the path to image if you can find it
*/
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = CalculateBill.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
JOptionPane.showMessageDialog(null, "Couldn't find file: " + path, "image path error", JOptionPane.ERROR_MESSAGE);
return null;
}
}
//Listens to the combo boxes
private void getSelectedMenuItem(JComboBox cb) {
String mnItem = (String) cb.getSelectedItem();
updateListBox(mnItem);
}
/**
* updates the list box
*
* #param name the element to be added to the list box
*/
private void updateListBox(String name) {
totallabel.setVisible(false);
model.addElement(name);
Addition(getPrices(name));
totallabel.setVisible(true);
}
void showWaiterAndTableNum() {
textArea.append("Table Number: " + tn + " Waiter: " + wn);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* adds to the subtotal/total calculator.
*
* #param s The name of the menu item which will be used to access its hashmap key value.
*
*/
private void Addition(double addedP) {
subtotal = subtotal + addedP;
tax = .0625 * subtotal;
total = subtotal + tax;
}
/**
* subtracts from to the subtotal/total calculator.
*
* #param subtractedp The price of the menu item which will be used to access its hashmap key value.
*
*/
// sets up the 'total' label which shows subtotal, tax, total
private void Subtraction(double subtractedp) {
subtotal = subtotal - subtractedp;
tax = subtotal * .0625;
total = subtotal + tax;
}
private void resetCalculator() {
subtotal = 0.00;
tax = 0.00;
total = 0.00;
}
// listens to list buttons
#Override
public void actionPerformed(ActionEvent e) {
JTextField tf = (JTextField) e.getSource();
if (tf.equals("textTableNum")) {
tn = tf.getText();
} else if (tf.equals("waiterName")) {
wn = tf.getText();
}
String cmd = e.getActionCommand();
if (cmd.equals("Delete")) {
totallabel.setVisible(false);
ListSelectionModel selmodel = list.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
String foodName = (String) list.getSelectedValue();
Subtraction(getPrices(foodName));
totallabel.setVisible(true);
//subtracts from the subtotal
if (index >= 0) {
model.remove(index);
}
} else if (cmd.equals("Clear all")) {
model.clear();
resetCalculator();
}
}
//combobox mouse listener
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JComboBox cb = (JComboBox) e.getSource();
getSelectedMenuItem(cb);
}
}
private String setTotalLabelAmount() {
String totlab = "Subtotal: $ " + subtotal + " Tax: $" + tax + "\n" + "Total: $ " + total;
return totlab;
}
}
This is not representative code of, well, anything. It's sole capability is that it functions to at least show something like what you were looking for.
Also note I commented out all of the logo code, since I didn't have the image file - I just punted on that part for the sake of expediency.
What it does is it create a JPanel subclass. That panel has a BoxLayout, that lines up vertically. You misunderstand how the BorderLayout works by putting multiple components in to the same slot. For example, you but both the 'Delete' and 'Clear All' JButton in to the BorderLayout.SOUTH. That means they both consume the same space, in the end one ends up on top of the other so it looks like only one component.
A BoxLayout has a Flow, that is as you add components to them, the components do not overlap and get added and expand the space. The basic JPanels layout is a vertical BoxLayout, so that as components are added, they will stack and appear in rows.
Next, a common idiom in Swing, especially with hand made GUIs, is you use JPanels as containers. If you ever used a drawing program and use the Group function to turn, say, 4 lines in to a single box, the JPanel in Swing and layouts works the same way. Each JPanel has its own layout, and then once completed, the JPanel is treated as a whole.
So, here I used the BoxLayout again, only this time using the LINE_AXIS style, which puts components end to end, laying them out in a line.
You can see I create several JPanels, set the layout to the BoxLayout, then add components to each individual JPanel, and then add these JPanels to the master JPanel. The components in the individual JPanels lay out end to end, but as they are added to the master JPanel, its BoxLayout stacks them top to bottom.
Note that the remnants of your BorderLayout details remains, because I didn't clean that up. I would remove all of that.
This is where I stopped, as the code compiles and shows the GUI, which should at least give you something to work with other than 400 lines of black box "nothings happening" code. It likely does not look quite like you imagined, that wasn't my goal either. I would play with the JPanel and sub-JPanel idiom and the layout managers until you get closer to what you want. The Java Swing tutorial linked from the Javadoc for Swing is pretty good, if a bit scattered. So, more reading is in store.
As others have mentioned, when starting out something like thing, you would be best to start off small (like getting 2 of the drop down boxes to work). Then you would only have a couple of things to focus on to get those to work, and then you can build on that toward a final project.
I hope this is helpful to get you on your way.
It seems there are a bunch of attributes, starting with waiterName that are declared but not initialized.
First off you should switch back from an Applet to a regular app. And create the JFrame in the main method instead of doing it in your panel:
Change your main class to:
public class Main{
public static void main(String[] args){
JFrame frame = new JFrame("Charlotte's Appletree Restaurant");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CalculateBill newContentPane = new CalculateBill();
frame.getContentPane().add(newContentPane);
frame.setPreferredSize(new Dimension(300, 600));
frame.setVisible(true);
}
The main part of your problem however appears to be that you aren't initializaing textTableNum before you try to add an ActionListener to it.
A NullPointerException happens whenever you try to access a variable that isn't referencing an actual object. To diagnosis them go go the line number and see what variables are being dereferenced on that line.
In this case the stack trace tells you that the exception is happening on line 186 of CalculateBill.java,, which is:
textTableNum.addActionListener(this);
So based on that line of code the only variable that can be a problem is textTableNum. You need to make sure that variable is initialized before you use it.
Your second problem that you mentioned in the comments is because you started adding components to the CalculateBill panel using GridBagConstraints when you declared CalculateBill to use a BorderLayout.
Also, I noticed you add several components to the same BorderLayout region. You can't do this. You can add only one. If you want multiple components in the NORTH region then you need to create a sub-panel, layout the components you want there, then add the sub-panel to the NORTH of the BorderLayout.

Categories

Resources