Multiple choice test GUI with serialization of Q&A - java

I'm working on a project for school in Java programming. I need to design a GUI that will take in questions and answers and store them in a file. It should be able to contain an unlimited number of questions. We have covered binary I/O.
How do I write the input they give to a file? How would I go about having them add multiple questions from this GUI?
package multiplechoice;
import java.awt.*;
import javax.swing.*;
public class MultipleChoice extends JFrame {
public MultipleChoice() {
/*
* Setting Layout
*/
setLayout(new GridLayout(10,10));
/*
* First Question
*/
add(new JLabel("What is the category of the question?: "));
JTextField category = new JTextField();
add(category);
add(new JLabel("Please enter the question you wish to ask: "));
JTextField question = new JTextField();
add(question);
add(new JLabel("Please enter the correct answer: "));
JTextField correctAnswer = new JTextField();
add(correctAnswer);
add(new JLabel("Please enter a reccomended answer to display: "));
JTextField reccomendedAnswer = new JTextField();
add(reccomendedAnswer);
add(new JLabel("Please enter a choice for multiple choice option "
+ "A"));
JTextField A = new JTextField();
add(A);
add(new JLabel("Please enter a choice for multiple choice option "
+ "B"));
JTextField B = new JTextField();
add(B);
add(new JLabel("Please enter a choice for multiple choice option "
+ "C"));
JTextField C = new JTextField();
add(C);
add(new JLabel("Please enter a choice for multiple choice option "
+ "D"));
JTextField D = new JTextField();
add(D);
add(new JButton("Compile Questions"));
add(new JButton("Next Question"));
}
public static void main(String[] args) {
/*
* Creating JFrame to contain questions
*/
FinalProject frame = new FinalProject();
// FileOutputStream output = new FileOutputStream("Questions.dat");
JPanel panel = new JPanel();
// button.setLayout();
// frame.add(panel);
panel.setSize(100,100);
// button.setPreferredSize(new Dimension(100,100));
frame.setTitle("FinalProject");
frame.setSize(600, 400);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

First:
There are basically two ways to write to a file in java.
ObjectOutputStream(FileOutputStream("blah")) API
PrintWriter("blah") API
Second:
Three or more; use a for.
This is what comes to mind for me when reading JTextField A = new JTextField(); and JTextField B = new JTextField();

Related

How to change the font of a string in gui and then change it back again to normal

Hello fellow programmers across the world I am currently having a problem with one of my frames in my GUI. I have managed to change the font of my messeges to itallic and the color to grey and i have set my textfield to editable(true). The problem is that when I delete the string in gray and italic and try to write something useful in the textfield, rather that plain font and a color of black for the string it always comes out italic and gray. Is there any way that a string in a text message can change font and color and then then next string you write to have the normal font and black color? Would appreciate any sugggestions at this point. Here is my code:
void makeSecondFrame(){
frame2 = new JFrame("Step one!Vertification!");
Container contentPane2 = frame2.getContentPane();
JLabel label2 = new JLabel("Welcome to step 1 of our algorithm, Verification!" + "To varify yourself of owning an account please enter the following:");
JLabel label3 = new JLabel("First Name:");
JLabel label4 = new JLabel("Middle Name:");
JLabel label5 = new JLabel("Surname:");
JLabel label6 = new JLabel("Account Number:");
JLabel label7 = new JLabel ("Registration Number:");
firstName = new TextField("Enter your name here");
firstName.setForeground(Color.gray);
firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
firstName.setEditable(true);
middleName = new TextField("Enter your middle name here");
middleName.setForeground(Color.gray);
middleName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
middleName.setEditable(true);
surname = new TextField("Enter your surname here");
surname.setForeground(Color.gray);
surname.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
surname.setEditable(true);
accountNumber = new TextField("Enter your main account number");
accountNumber.setForeground(Color.gray);
accountNumber.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
accountNumber.setEditable(true);
registrationNumber = new TextField("Enter your registration number");
registrationNumber.setForeground(Color.gray);
registrationNumber.setFont(new java.awt.Font("Arail", Font.ITALIC, 12));
registrationNumber.setEditable(true);
JPanel p2 = new JPanel(new GridLayout(1,1));
p2.add(label2);
contentPane2.add(p2, BorderLayout.NORTH);
JPanel p3 = new JPanel(new GridLayout(10,1));
p3.add(label3);
p3.add(firstName);
p3.add(label4);
p3.add(middleName);
p3.add(label5);
p3.add(surname);
p3.add(label7);
p3.add(registrationNumber);
p3.add(label6);
p3.add(accountNumber);
contentPane2.add(p3, BorderLayout.WEST);
JButton next = new JButton("Next!");
next.addActionListener(this);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(this);
JPanel p4 = new JPanel(new GridLayout(1,1));
p4.add(next);
p4.add(cancel);
contentPane2.add(p4, BorderLayout.SOUTH);
frame2.pack();
frame2.setVisible(true);
}
You need to act on an appropriate action on the JTextField. The best I can think of is the FocusListener.focusGained():
firstName = new TextField("Enter your name here");
firstName.setForeground(Color.gray);
firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
firstName.setEditable(true);
firstName.addFocuListener(new FocusAdapter(){
#Overwrite
public void focusGained(FocusEvent e){
firstName.setText("");// remove help message, will also remove previously entered text!
firstName.setFont(new JTextField().getFont()); // reset to default
}
}
Well that did remove the helper message – Христо Петков
as I mentioned...
and I want to keep it – Христо Петков
Then you might want to use the other method in the FocusListener interface too:
#Overwrite
public void focusLost(FocusEvent e){
if(userDidNotEnterTextIn(firstName){ // hopefully you know how to find out...
firstName.setText("Enter your name here");
// do formatting again
}
}

How to add validation to multiple text fields in JOptionPane?

I have the following method which pops up a window when a button is clicked.
public void cardPopUp() {
String[] cardTypes = {"Visa", "Mastercard", "Electron", "Cashcard"};
JComboBox combo = new JComboBox(cardTypes);
JTextField field1 = new JTextField("");
JTextField field2 = new JTextField("");
JTextField field3 = new JTextField("");
JTextField field4 = new JTextField("");
JTextField field5 = new JTextField("");
JPanel panel = new JPanel(new GridLayout(0, 2));
panel.add(new JLabel("Card Type:"));
panel.add(combo);
panel.add(new JLabel("Cardholder Name:"));
panel.add(field1);
panel.add(new JLabel("Card Number:"));
panel.add(field2);
panel.add(new JLabel("Month Expiry:"));
panel.add(field3);
panel.add(new JLabel("Year Expiry:"));
panel.add(field4);
panel.add(new JLabel("CVC:"));
panel.add(field5);
int input = JOptionPane.showConfirmDialog(MainActivity.this, panel, "Card Payment",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (input == JOptionPane.OK_OPTION) {
Basket.orderNo+=1;
dispose();
new OrderConfirmationScreen().setVisible(true);
} else {
System.out.println("Payment Cancelled");
}
}
How can i add validation so that the fields are checked to see if correct data was entered for a card payment. For example, field1 should only allow text, field2 should only allow a 16 digit number and so on.
I'm guessing i would need to create more methods that validate each field and then just call the method in cardPopUp() method.
For example :
field1 should only allow text
if(field1.getText().matches("\\w+\\.?")){
...
}else{...}
field2 should only allow a 16 digit number
if(field2.getText().matches("(\\d{16})")){
...
}else{...}
And so on.
as i understand your question what u want is to match the character types that are inputted, for this i would suggest to take a look at the String.matches see javaDoc using this you can setup a function that checks the input for any regrex epression and returns true or false, if this is NOT what you wanted i'm afraid i don't understand the question

How to plus 2 JTextField numbers?

I want to add two numbers and put the result into a JTextFields (textboxes). Why doesn't this code work?
public class Window extends JFrame implements ActionListener {
private JButton plus;
private JLabel text;
private JTextField textbox1;
private JTextField textbox2;
public Okno(){
this.setLayout(new FlowLayout());
this.setBounds(400,400,400,400);
plus = new JButton("+");
text = new JLabel("");
plus.addActionListener(this);
textbox1 = new JTextField(" ");
textbox2 = new JTextField(" ");
this.add(text);
this.add(textbox1);
this.add(textbox2);
this.add(plus);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(plus)){
int result = Integer.valueOf(textbox1.getText()) + Integer.valueOf(textbox2.getText());
text.setText(Integer.toString(result)); //gtregergregergergreg
}
}
}
Thank you for your help.
It works, if you remove spaces while putting numbers to the text fields, otherwise you get NumberFormatException. By the way don't use spaces for aligning the text fields. You can use setColumns or different layout manager. Also you should validate input to be sure there are just numbers, if you want to add them together.
Delete spaces from:
textbox1 = new JTextField(" ");
textbox2 = new JTextField(" ");
cause while parsing to Integer it fails.
Set prefered size of textbox1 and textbox2:
textbox1 = new JTextField();
textbox1.setPreferredSize(new Dimension(20,20));
textbox2 = new JTextField();
textbox2.setPreferredSize(new Dimension(20,20));
Hope I helped :)

Recording user choice java

I have a scroll box where a user can choose between options. If I want the user's choice to print elsewhere, what will I need to call? I already have where I want the user choice.
results.setText();
What would go in the parenthesis?
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.awt.event.*;
public class container implements ActionListener
{
JPanel panels;
Timer timer;
JTextField userTypingRegion;
JTextArea results;
JComboBox<Integer> ageEntries;
JComboBox<String> raceList;
public void init(Container pane)
{
JButton switcher = new JButton("Next / Back");
switcher.addActionListener(this);
JPanel infoPage = new JPanel();
infoPage.setBackground(Color.BLACK);
//CENTER
JPanel panelCenter = new JPanel();
panelCenter.setBackground(Color.GRAY);
panelCenter.setLayout(new BoxLayout(panelCenter, BoxLayout.Y_AXIS));
infoPage.add(BorderLayout.CENTER, panelCenter);
///Gender
JPanel genderSelection = new JPanel();
JLabel gender = new JLabel("Gender:");
JCheckBox checkGenderMale = new JCheckBox("Male");
JCheckBox checkGenderFemale = new JCheckBox("Female");
genderSelection.add(gender);
genderSelection.add(checkGenderMale);
genderSelection.add(checkGenderFemale);
panelCenter.add(genderSelection);
///Age
JPanel ageSelection = new JPanel();
JLabel age = new JLabel("Age:");
ArrayList<Integer> ageList = new ArrayList<Integer> ();
for (int i = 1; i <= 100; ++i)
{
ageList.add(i);
}
DefaultComboBoxModel<Integer> modelAge = new DefaultComboBoxModel<Integer>();
for (Integer i : ageList)
{
modelAge.addElement(i);
}
JComboBox<Integer> ageEntries = new JComboBox<Integer>();
ageEntries.setModel(modelAge);
ageSelection.add(age);
ageSelection.add(ageEntries);
panelCenter.add(ageSelection);
///Race
JPanel raceSelection = new JPanel();
JLabel race = new JLabel("Race/Ethnicity:");
String[] raceEntries = {"White", "Black", "Hispanic"
, "Asian/Pacific Islander"
, "Alaska Native/American Indian", "Confused"};
JComboBox<String> raceList = new JComboBox<String>(raceEntries);
raceList.addActionListener(new transferInfo());
raceSelection.add(race);
raceSelection.add(raceList);
panelCenter.add(raceSelection);
///Question 1
JPanel firstQuestion = new JPanel();
JLabel one = new JLabel("How often do you read?");
String[] oneEntries = {"Always", "Often", "Sometimes"
, "Not Often", "What is reading?"};
JComboBox<String> oneAnswer = new JComboBox<String>(oneEntries);
firstQuestion.add(one);
firstQuestion.add(oneAnswer);
panelCenter.add(firstQuestion);
///Question 2
JPanel secondQuestion = new JPanel();
JLabel two = new JLabel("Average time (in minutes) " +
"spent on the computer per day:");
ArrayList<Integer> hourList = new ArrayList<Integer>();
for (int z = 0; z <= 1440; z = z + 30)
{
hourList.add(z);
}
DefaultComboBoxModel<Integer> modelHour = new DefaultComboBoxModel<Integer>();
for (Integer z : hourList)
{
modelHour.addElement(z);
}
JComboBox<Integer> hourEntries = new JComboBox<Integer>();
hourEntries.setModel(modelHour);
secondQuestion.add(two);
secondQuestion.add(hourEntries);
panelCenter.add(secondQuestion);
///Question 3
JPanel thirdQuestion = new JPanel();
JLabel three = new JLabel("Favorite Subject");
String[] threeEntries = {"English", "Math", "Science"
, "Foreign Languages", "History", "Hate them all"};
JComboBox<String> threeAnswer = new JComboBox<String>(threeEntries);
thirdQuestion.add(three);
thirdQuestion.add(threeAnswer);
panelCenter.add(thirdQuestion);
///Question 4
JPanel fourthQuestion = new JPanel();
JLabel four = new JLabel("Average sleep (in minutes) per night:");
ArrayList<Integer> sleepTimeList = new ArrayList<Integer>();
for (int y = 0; y <= 1440; y = y + 30)
{
sleepTimeList.add(y);
}
DefaultComboBoxModel<Integer> modelSleepTime = new DefaultComboBoxModel<Integer>();
for (Integer z : sleepTimeList)
{
modelSleepTime.addElement(z);
}
JComboBox<Integer> sleepTimeEntries = new JComboBox<Integer>();
sleepTimeEntries.setModel(modelSleepTime);
fourthQuestion.add(four);
fourthQuestion.add(sleepTimeEntries);
panelCenter.add(fourthQuestion);
///Question 5
JPanel fifthQuestion = new JPanel();
JLabel five = new JLabel("I am...");
String [] fiveEntries = {"Outgoing", "In the middle", "Shy"};
JComboBox<String> fiveAnswer = new JComboBox<String>(fiveEntries);
fifthQuestion.add(five);
fifthQuestion.add(fiveAnswer);
panelCenter.add(fifthQuestion);
///Question 6
JPanel sixthQuestion = new JPanel();
JLabel six = new JLabel("I am...");
String [] sixEntries = {"Adventurous", "In the middle", "Lazy"};
JComboBox<String> sixAnswer = new JComboBox<String>(sixEntries);
sixthQuestion.add(six);
sixthQuestion.add(sixAnswer);
panelCenter.add(sixthQuestion);
///Question 7
JPanel seventhQuestion = new JPanel();
JLabel seven = new JLabel("I live in the...");
String [] sevenEntries = {"City", "Suburb", "Country", "Narnia"};
JComboBox<String> sevenAnswer = new JComboBox<String>(sevenEntries);
seventhQuestion.add(seven);
seventhQuestion.add(sevenAnswer);
panelCenter.add(seventhQuestion);
///Question 8
JPanel eighthQuestion = new JPanel();
JLabel eight = new JLabel("Please choose the painting you like.");
eighthQuestion.add(eight);
panelCenter.add(eighthQuestion);
///Adding Picture
JPanel pictures = new JPanel();
ImageIcon image = new ImageIcon("C:\\Users\\Kevin\\Desktop\\Left and Right.jpg");
JLabel imageButton = new JLabel();
imageButton.setIcon(image);
pictures.add(imageButton);
panelCenter.add(pictures);
///Question 9
JPanel ninthQuestion = new JPanel();
JCheckBox checkLeft = new JCheckBox("I like the left one!");
JCheckBox checkRight = new JCheckBox("I like the right one!");
ninthQuestion.add(checkLeft);
ninthQuestion.add(checkRight);
panelCenter.add(ninthQuestion);
////Second Card
JPanel programFrame = new JPanel();
programFrame.setBackground(Color.BLACK);
programFrame.setMinimumSize(new Dimension(200, 300));
programFrame.setMaximumSize(new Dimension(800, 700));
programFrame.setPreferredSize(new Dimension(500, 500));
///CENTER DATA COLLECTION REGION
JPanel dataCollectionRegion = new JPanel();
dataCollectionRegion.setBackground(Color.LIGHT_GRAY);
dataCollectionRegion.setLayout(
new BoxLayout(dataCollectionRegion, BoxLayout.Y_AXIS));
programFrame.add(BorderLayout.CENTER, dataCollectionRegion);
///South Region
JPanel southRegion = new JPanel();
southRegion.setBackground(Color.BLACK);
southRegion.setLayout(new BoxLayout(southRegion, BoxLayout.Y_AXIS));
programFrame.add(BorderLayout.NORTH, southRegion);
///Data Components
JLabel sampleWriting = new JLabel("<html>7 Dear friends, let us love one another, for love comes from God. <br>Everyone who loves has been born of God and knows God. 8 Whoever <br>does not love does not know God, because God is love. 9 This is how <br>God showed his love among us: He sent his one and only Son into <br>the world that we might live through him. 10 This is love: not that we <br>loved God, but that he loved us and sent his Son as an atoning sacrifice <br> for our sins. 11 Dear friends, since God so loved us, we also ought <br>to love one another. 12 No one has ever seen God; but if we love one <br> another, God lives in us and his love is made complete in us. <br> 1 Everyone who believes that Jesus is the Christ is born of God, and everyone <br> who loves the father loves his child as well. 2 This is how we know <br> that we love the children of God: by loving God and carrying out his commands. <br> 3 In fact, this is love for God: to keep his commands. And his commands <br> are not burdensome, 4 for everyone born of God overcomes the world. <br> This is the victory that has overcome the world, even our faith. 5 Who <br> is it that overcomes the world? Only the one who believes that Jesus is the Son of God.</html>");
userTypingRegion = new JTextField();
userTypingRegion.addActionListener( this);
dataCollectionRegion.add(sampleWriting);
dataCollectionRegion.add(userTypingRegion);
///Instructions South
JLabel instructions = new JLabel("Instruction: Type the " +
"passage as fast as possible in the space provided.");
instructions.setForeground(Color.white);
JLabel showResult = new JLabel("- - - Results - - -");
showResult.setForeground(Color.white);
showResult.setHorizontalTextPosition(JLabel.CENTER);
results = new JTextArea();
results.setEditable(false);
southRegion.add(instructions);
southRegion.add(Box.createRigidArea(new Dimension(0,5)));
southRegion.add(showResult);
southRegion.add(Box.createRigidArea(new Dimension(0,5)));
southRegion.add(results);
///add cards
panels = new JPanel(new CardLayout());
panels.add(infoPage);
panels.add(programFrame);
pane.add(switcher, BorderLayout.PAGE_START);
pane.add(panels, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent evt)
{
CardLayout layout = (CardLayout)(panels.getLayout());
layout.next(panels);
}
class transferInfo implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
results.setText("Selected: " + raceList.getSelectedItem());
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Biometric Keystroke Dynamics");
container TabChanger = new container();
TabChanger.init(frame.getContentPane());
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
You can see my attempt at resolving this issue near the end of the code. I apologize in advance for my messy coding. (it is my first)
First of all the mistakes you are committing in your code :
You are declaring JComboBox<Integer> ageEntries; and JComboBox<String> raceList; as your instance variables and as your localvariables inside your init(...) method. Don't declare them twice, use only the instance variables or the local variables, as the need be, but do not use them twice.
Always make this a habit of yours to add this ilne frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); as you make an object of JFrame, this helps in shutting down the JFrame window in a good manner.
Now for what to write in results.setText(); . You can make one validation method inside your container class, which will return boolean and will be called inside the actionPerformed(...) method of the NextButton and inside this method check the values as entered by the user as legitimate or not, if they are legal values then use StringBuilder to append it like say
StringBuilder sb = new StringBuilder(); // this will be your instance variable not local.
sb.append((String) ageEntries.getSelectedItem());
sb.append(" "); // Add this space to distinguish between two values.
// and so on for other values.
Once done you can write results.setText(containerObject.sb.toString()); to show these values.

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