Java: Action Handler - java

I am working on a problem for school and I am having an issue with the CalculateButtonHandler. I am also using an ExitButtonHandler but that is not giving me any issues. I have tried re-reading my textbook and have searched the web. After racking my brain over this issue I can't figure out why this won't work. This is my first GUI attempt and I am sure I will have to mess with the program to get it the way I want. I only want to know how to fix this CalculateButtonHandler issues as I can work on the rest if need be. Below is the code for the project.
Issues:
Lines 38, 76 and 77: CalculateButtonHandler cannot be resolved to a type.
What does this mean and how can I go about fixing it?
//This program calculates the weighted average of four test scores.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.math.*;
public class SNHU6_4 extends JFrame
{
private static final int WIDTH = 400;
private static final int LENGTH = 300;
private JLabel testscore1L;
private JLabel weight1L;
private JLabel testscore2L;
private JLabel weight2L;
private JLabel testscore3L;
private JLabel weight3L;
private JLabel testscore4L;
private JLabel weight4L;
private JLabel scoreL;
private JTextField testscore1TF;
private JTextField weight1TF;
private JTextField testscore2TF;
private JTextField weight2TF;
private JTextField testscore3TF;
private JTextField weight3TF;
private JTextField testscore4TF;
private JTextField weight4TF;
private JTextField scoreTF;
private JButton calculateB;
private JButton exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public SNHU6_4()
{
//Creating the labels
testscore1L = new JLabel ("Enter first test score: ", SwingConstants.RIGHT);
testscore2L = new JLabel ("Enter second test score: ", SwingConstants.RIGHT);
testscore3L = new JLabel ("Enter third test score: ", SwingConstants.RIGHT);
testscore4L = new JLabel ("Enter fourth test score: ", SwingConstants.RIGHT);
weight1L = new JLabel ("Enter first test score weight : ", SwingConstants.RIGHT);
weight2L = new JLabel ("Enter second test score weight :", SwingConstants.RIGHT);
weight3L = new JLabel ("Enter third test score weight :", SwingConstants.RIGHT);
weight4L = new JLabel ("Enter fourth test score weight :", SwingConstants.RIGHT);
scoreL = new JLabel ("Final score: ", SwingConstants.RIGHT);
//Creating the text fields
testscore1TF = new JTextField ("0",5);
testscore1TF.setHorizontalAlignment(JTextField.CENTER);
testscore2TF = new JTextField ("0",5);
testscore1TF.setHorizontalAlignment(JTextField.CENTER);
testscore3TF = new JTextField ("0",5);
testscore3TF.setHorizontalAlignment(JTextField.CENTER);
testscore4TF = new JTextField ("0",5);
testscore4TF.setHorizontalAlignment(JTextField.CENTER);
weight1TF = new JTextField ("0",5);
weight1TF.setHorizontalAlignment(JTextField.CENTER);
weight2TF = new JTextField ("0",5);
weight2TF.setHorizontalAlignment(JTextField.CENTER);
weight3TF = new JTextField ("0",5);
weight3TF.setHorizontalAlignment(JTextField.CENTER);
weight4TF = new JTextField ("0",5);
weight4TF.setHorizontalAlignment(JTextField.CENTER);
scoreTF = new JTextField ("0",5);
scoreTF.setHorizontalAlignment(JTextField.CENTER);
//Creating the calculate button
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
//Creating the exit button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
//Creating the window title
setTitle ("Weighted Average of Test Scores");
//Get the container
Container pane = getContentPane();
//Set the layout
pane.setLayout(new GridLayout(5, 4));
//Placing components in the pane
pane.add(testscore1L);
pane.add(testscore1TF);
pane.add(testscore2L);
pane.add(testscore2TF);
pane.add(testscore3L);
pane.add(testscore3TF);
pane.add(testscore4L);
pane.add(testscore4TF);
pane.add(weight1L);
pane.add(weight1TF);
pane.add(weight2L);
pane.add(weight2TF);
pane.add(weight3L);
pane.add(weight3TF);
pane.add(weight4L);
pane.add(weight4TF);
pane.add(calculateB);
pane.add(exitB);
//Set the window size
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHanlder implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double testscore1, testscore2, testscore3, testscore4;
double weight1, weight2, weight3, weight4;
double average1, average2, average3, average4;
double totalAverage;
testscore1 = Double.parseDouble(testscore1TF.getText());
testscore2 = Double.parseDouble(testscore2TF.getText());
testscore3 = Double.parseDouble(testscore3TF.getText());
testscore4 = Double.parseDouble(testscore4TF.getText());
weight1 = Double.parseDouble(weight1TF.getText());
weight2 = Double.parseDouble(weight2TF.getText());
weight3 = Double.parseDouble(weight3TF.getText());
weight4 = Double.parseDouble(weight4TF.getText());
average1 = testscore1 * weight1;
average2 = testscore2 * weight2;
average3 = testscore3 * weight3;
average4 = testscore4 * weight4;
totalAverage = average1 + average2 + average3 + average4;
scoreTF.setText("" + String.format("%,2f", totalAverage));
}
}
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
SNHU6_4 rectObject = new SNHU6_4();
}
}

CalculateButtonHandler cannot be resolved to a type
Is telling you it can't find a class by that name:
private class CalculateButtonHanlder implements ActionListener
You have a typo "Hanlder"
private class CalculateButtonHandler implements ActionListener

You spelled `CalculateButtonHandler' as 'CalculateButtonHanlder' when you declared the class on line 120. Fix that and it will work.

Related

Double cannot be converted to JTextField

On lines, 139 - 146 the error "Double cannot be converted to JTextField" comes up. I understand that I need to change the name of the variable but I am unsure where to change it. I've attempted to change the names under CalcButtonListener but it created more errors. Thank you for your time and help!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TravelExpenses extends JFrame
{
private JPanel panel;
private JPanel buttonPanel;
private JTextField numDays;
private JTextField airfare;
private JTextField carRent;
private JTextField miles;
private JTextField parking;
private JTextField taxi;
private JTextField reg;
private JTextField lodge;
private JButton calcButton;
private JButton resetButton;
public TravelExpenses()
{
setTitle("Travel Expenses");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
buildButtonPanel();
add(panel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
private void buildPanel()
{
//labels for text fields
JLabel numDaysLabel = new JLabel("Number of days of the trip:");
JLabel airfareLabel = new JLabel("Amount of airfare:");
JLabel carRentLabel = new JLabel("Amount of car rental:");
JLabel milesLabel = new JLabel("Miles driven(if a private vehicle was used):");
JLabel parkingLabel = new JLabel("Parking fees:");
JLabel taxiLabel = new JLabel("Taxi fees:");
JLabel regLabel = new JLabel("Conference registaration:");
JLabel lodgeLabel = new JLabel("Lodging charges per night:");
//text fields
numDays = new JTextField(10);
airfare = new JTextField(10);
carRent = new JTextField(10);
miles = new JTextField(10);
parking = new JTextField(10);
taxi = new JTextField(10);
reg = new JTextField(10);
lodge = new JTextField(10);
//new panel
panel = new JPanel();
//layout manager
panel.setLayout(new GridLayout( 10,8));
//add labels and text fields
panel.add(numDaysLabel);
panel.add(numDays);
panel.add(airfareLabel);
panel.add(airfare);
panel.add(carRentLabel);
panel.add(carRent);
panel.add(milesLabel);
panel.add(miles);
panel.add(parkingLabel);
panel.add(parking);
panel.add(taxiLabel);
panel.add(taxi);
panel.add(regLabel);
panel.add(reg);
panel.add(lodgeLabel);
panel.add(lodge);
//put border around panel
panel.setBorder(BorderFactory.createEmptyBorder(10,10, 1, 10));
}
//method creates button panel
private void buildButtonPanel()
{
//create button for calc
calcButton = new CButton("Calculate");
calcButton.addActionListener(new CalcButtonListener());
resetButton = new JButton("Reset");
resetButton.addActionListener(new ResetButtonListener());
buttonPanel = new JPanel();
buttonPanel.add(resetButton);
buttonPanel.add(calcButton);
}
//listener for calc button
private class CalcButtonListener implements ActionListener
{
double numDays;
double airfare;
double carRent;
double miles;
double parking;
double taxi;
double reg;
double lodge;
public void actionPerformed(Action e)
{
double total;
String msg;
//get data
getData();
//total
total = determineTotal();
msg = String.format("Total cost: $%,.2f\n", total);
JOptionPane.showMessageDialog(null, msg);
}
}
**Below is the chunk I am having issues with**
private void getData()
{
numDays = Double.parseDouble(numDays.getText());
airfare = Double.parseDouble(airfare.getText());
carRent = Double.parseDouble(carRent.getText());
miles = Double.parseDouble(miles.getText());
parking = Double.parseDouble(parking.getText());
taxi = Double.parseDouble(taxi.getText());
reg = Double.parseDouble(reg.getText());
lodge = Double.parseDouble(lodge.getText());
}
On lines, 139 - 146 you are accessing members of TravelExpenses class rather than CalcButtonListener class.
Put getData() and determineTotal() method in CalcButtonListener class and use scope specifiers of particular member like for JtextField use:TravelExpenses.this.numDays as like for all JtextField.
Use below code for CalcButtonListener:
private class CalcButtonListener implements ActionListener
{
double numDays;
double airfare;
double carRent;
double miles;
double parking;
double taxi;
double reg;
double lodge;
public void actionPerformed(Action e)
{
double total;
String msg;
//get data
getData();
//total
total = determineTotal();
msg = String.format("Total cost: $%,.2f\n", total);
JOptionPane.showMessageDialog(null, msg);
}
private void getData()
{
numDays = Double.parseDouble(TravelExpenses.this.numDays.getText());
airfare = Double.parseDouble(TravelExpenses.this.airfare.getText());
carRent = Double.parseDouble(TravelExpenses.this.carRent.getText());
miles = Double.parseDouble(TravelExpenses.this.miles.getText());
parking = Double.parseDouble(TravelExpenses.this.parking.getText());
taxi = Double.parseDouble(TravelExpenses.this.taxi.getText());
reg = Double.parseDouble(TravelExpenses.this.reg.getText());
lodge = Double.parseDouble(TravelExpenses.this.lodge.getText());
}
private double determineTotal()
{
double total = numDays * airfare * carRent * miles * parking * taxi * reg * lodge;
return total;
}
}
Here you can find complete code.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TravelExpenses extends JFrame {
private JPanel panel;
private JPanel buttonPanel;
private JTextField numDays;
private JTextField airfare;
private JTextField carRent;
private JTextField miles;
private JTextField parking;
private JTextField taxi;
private JTextField reg;
private JTextField lodge;
private JButton calcButton;
private JButton resetButton;
public TravelExpenses() {
setTitle("Travel Expenses");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
buildButtonPanel();
add(panel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
private void buildPanel() {
// labels for text fields
JLabel numDaysLabel = new JLabel("Number of days of the trip:");
JLabel airfareLabel = new JLabel("Amount of airfare:");
JLabel carRentLabel = new JLabel("Amount of car rental:");
JLabel milesLabel = new JLabel("Miles driven(if a private vehicle was used):");
JLabel parkingLabel = new JLabel("Parking fees:");
JLabel taxiLabel = new JLabel("Taxi fees:");
JLabel regLabel = new JLabel("Conference registaration:");
JLabel lodgeLabel = new JLabel("Lodging charges per night:");
// text fields
numDays = new JTextField(10);
airfare = new JTextField(10);
carRent = new JTextField(10);
miles = new JTextField(10);
parking = new JTextField(10);
taxi = new JTextField(10);
reg = new JTextField(10);
lodge = new JTextField(10);
// new panel
panel = new JPanel();
// layout manager
panel.setLayout(new GridLayout(10, 8));
// add labels and text fields
panel.add(numDaysLabel);
panel.add(numDays);
panel.add(airfareLabel);
panel.add(airfare);
panel.add(carRentLabel);
panel.add(carRent);
panel.add(milesLabel);
panel.add(miles);
panel.add(parkingLabel);
panel.add(parking);
panel.add(taxiLabel);
panel.add(taxi);
panel.add(regLabel);
panel.add(reg);
panel.add(lodgeLabel);
panel.add(lodge);
// put border around panel
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 1, 10));
}
//method creates button panel
private void buildButtonPanel() {
// create button for calc
calcButton = new CButton("Calculate");
calcButton.addActionListener(new CalcButtonListener());
resetButton = new JButton("Reset");
resetButton.addActionListener(new ResetButtonListener());
buttonPanel = new JPanel();
buttonPanel.add(resetButton);
buttonPanel.add(calcButton);
}
//listener for calc button
private class CalcButtonListener implements ActionListener {
double numDays;
double airfare;
double carRent;
double miles;
double parking;
double taxi;
double reg;
double lodge;
public void actionPerformed(ActionEvent e) {
double total;
String msg;
// get data
getData();
// total
total = determineTotal();
msg = String.format("Total cost: $%,.2f\n", total);
JOptionPane.showMessageDialog(null, msg);
}
private void getData() {
numDays = Double.parseDouble(TravelExpenses.this.numDays.getText());
airfare = Double.parseDouble(TravelExpenses.this.airfare.getText());
carRent = Double.parseDouble(TravelExpenses.this.carRent.getText());
miles = Double.parseDouble(TravelExpenses.this.miles.getText());
parking = Double.parseDouble(TravelExpenses.this.parking.getText());
taxi = Double.parseDouble(TravelExpenses.this.taxi.getText());
reg = Double.parseDouble(TravelExpenses.this.reg.getText());
lodge = Double.parseDouble(TravelExpenses.this.lodge.getText());
}
private double determineTotal() {
double total = numDays * airfare * carRent * miles * parking * taxi * reg * lodge;
return total;
}
}
private class ResetButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// reset text fields
numDays.setText("0");
airfare.setText("0");
carRent.setText("0");
miles.setText("0");
parking.setText("0");
taxi.setText("0");
reg.setText("0");
lodge.setText("0");
}
}
public static void main(String[] args) {
TravelExpenses gc = new TravelExpenses();
}
}

Travel expenses GUI "Calculate reimbursement" button not responding

I can get the input box to appear, and can enter all of my data. The reset button works, but I cannot figure out why the calculate button refuses to show the output reimbursement.
import java.awt.*;
import javax.swing.*;
import java.text.DecimalFormat;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class TravelExpenses extends JFrame{
//info for labels
private JLabel daysOnTrip;
private JLabel carRental;
private JLabel airfair;
private JLabel parkingFees;
private JLabel taxiFees;
private JLabel milesDriven;
private JLabel conReg;
private JLabel lodgingNightCharges;
//reference panel obs
private JPanel travelInfo;
private JPanel buttonP;
//info from fields of texts
private JTextField daysOnTripText;
private JTextField carRentalText;
private JTextField airfairText;
private JTextField parkingFeesText;
private JTextField taxiFeesText;
private JTextField milesDrivenText;
private JTextField conRegText;
private JTextField lodgingNightChargesText;
//buttons that will be used to function
private JButton calculate; //will be used to calculate informaiton that the user enters when clicked
private JButton reset; // will be used to reset the fields as needed when clicked
//constants as specified
private double mealsCost = 37.00; //per day for meals
private double parkingFeesAmount = 10.00; // up to 10 per day
private double taxiFeesAmount = 20.00; // up to 20 per day
private double lodgingChargesAmount = 95.00; // up to 95 a day
private double mileAmount = 0.27; //per mile driven
/**
* Constructor
* #param args
*/
public TravelExpenses(){
//JFrame title called
super("Travel Expenses");
//center of desktop placement
setLocationRelativeTo(null);
//Close button will do this..
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//border layout mgr cp
setLayout(new BorderLayout());
//TravelInfo&Buttons
buildTravelInfoPanel();
buildButton();
// get panels to frame content
add(travelInfo, BorderLayout.CENTER);
add(buttonP, BorderLayout.SOUTH);
//window content display
pack();
setVisible(true);
}
private void buildTravelInfoPanel(){
//field labels made
daysOnTrip = new JLabel("Number of days for trip.");
airfair = new JLabel("Airfair Amount: ");
carRental = new JLabel ("Car Rental Cost Amount: ");
milesDriven = new JLabel ("Mile Driven: ");
parkingFees = new JLabel ("Parking Fees: ");
taxiFees = new JLabel ("Taxi Fees: ");
conReg = new JLabel ("Conference Registration Cost: ");
lodgingNightCharges = new JLabel ("Lodging Charges per Night: ");
//text boxes for input from user
daysOnTripText = new JTextField(3);
carRentalText = new JTextField(8);
airfairText = new JTextField(8);
parkingFeesText = new JTextField(6);
taxiFeesText = new JTextField(6);
milesDrivenText = new JTextField(4);
conRegText = new JTextField(8);
lodgingNightChargesText = new JTextField(6);
//panel for labels/text
travelInfo = new JPanel();
//Grid for 10 r and 2 c
travelInfo.setLayout(new GridLayout(10,2));
//labels and text for panel made
travelInfo.add(daysOnTrip);
travelInfo.add(daysOnTripText);
travelInfo.add(airfair);
travelInfo.add(airfairText);
travelInfo.add(carRental);
travelInfo.add(carRentalText);
travelInfo.add(milesDriven);
travelInfo.add(milesDrivenText);
travelInfo.add(parkingFees);
travelInfo.add(parkingFeesText);
travelInfo.add(taxiFees);
travelInfo.add(taxiFeesText);
travelInfo.add(conReg);
travelInfo.add(conRegText);
travelInfo.add(lodgingNightCharges);
travelInfo.add(lodgingNightChargesText);
}
/**
* buildButton is method that adds reset and calc buttons to main panel
* #param args
*/
private void buildButton(){
//caclulation button
calculate = new JButton("Calculate Reimbursment");
//event listiner for calculation
calculate.addActionListener(new CalculateListener());
//reset button
reset = new JButton("Reset");
//event listiner for reset
reset.addActionListener(new ResetListener());
//button panels
buttonP = new JPanel();
//buttons
buttonP.add(reset, BorderLayout.WEST);
buttonP.add(calculate, BorderLayout.CENTER);
}
/**
* CalculateListener will do event for calculate button
* #param args
*/
private class CalculateListener implements ActionListener{
//variables
String input;
int days;
double air;
double miles;
double carRental;
double conReg;
double lodging;
double parking;
double meals;
double taxi;
public void actionPerformed(ActionEvent e){
//variables
double actualExpenses;
double milesExpenses;
double allowed;
double exAirfair;
double exCarRen;
double exParking;
double exTaxi;
double exLodge;
double overTotal;
double savings;
double reimb;
//dec format implement
DecimalFormat money = new DecimalFormat("$#,###.00");
}
//get info from text fields
private void getInfo(){
days = Integer.parseInt(daysOnTripText.getText());
air = Double.parseDouble(airfairText.getText());
carRental = Double.parseDouble(carRentalText.getText());
miles = Double.parseDouble(milesDrivenText.getText());
parking = Double.parseDouble(parkingFeesText.getText());
taxi = Double.parseDouble(parkingFeesText.getText());
conReg = Double.parseDouble(conRegText.getText());
lodging = Double.parseDouble(lodgingNightChargesText.getText());
}
//figure out expenses
private void calcActualExpenses(double actualExpenses, double milesExpenses){
actualExpenses = air + carRental + parking + taxi + conReg + lodging;
milesExpenses = miles * mileAmount;
actualExpenses = actualExpenses + milesExpenses;
//display total
JOptionPane.showMessageDialog(null, "Total expenses: " + "\n"+
"Allowables expenses: " + "\n" +
"\n" + "Amount to be paid back: ");
}
}
//this handles reset button
private class ResetListener implements ActionListener{
public void actionPerformed(ActionEvent e){
daysOnTripText.setText("");
airfairText.setText("");
carRentalText.setText("");
milesDrivenText.setText("");
parkingFeesText.setText("");
taxiFeesText.setText("");
conRegText.setText("");
lodgingNightChargesText.setText("");
}
}
public static void main(String[] args) {
new TravelExpenses();
}
}
I can get the input box to appear, and can enter all of my data. The reset button works, but I cannot figure out why the calculate button refuses to show the output reimbursement.

Main method's New Instance ignored [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Hello everyone and a good day to you.
I'm having trouble with this swing based GUI program that is considerably not finished. However, it should compile and run at least. Unfortunately it doesn't, and I suspect it's because the main method call is being ignored. The error appears to be happening at the part where the panel with the JSliders is being built, but it's not being any more specific than that. What is happening?
>
package charactercreationquest;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.border.TitledBorder;
public class CharacterCreationQuest extends JFrame {
//contains: image, race, raceLabel, job, jobLabel, genderLabel male, and female.
private final JPanel picPanel;
//contains: str, intel, dex, wis, ptsSpent, and ptsRemain.
private final JPanel sliderPanel;
//contains: name, and nameLabel
private final JPanel namePanel;
//contains: save and load
private final JPanel savePanel;
private JSlider str;
private JSlider intel;
private JSlider dex;
private JSlider wis;
private JTextField name;
private JComboBox race;
private JComboBox job;
private JRadioButton male;
private JRadioButton female;
private JButton save;
private JButton load;
private JLabel image;
private JLabel genderLabel;
private JLabel nameLabel;
private JLabel jobLabel;//Label for lifestyles
private JLabel raceLabel;
private JLabel strLabel;
private JLabel intelLabel;
private JLabel dexLabel;
private JLabel wisLabel;
private JLabel ptsRemain;
private JLabel ptsSpent;
//what the heck is OCA look it up dumbo
public CharacterCreationQuest()
{
picPanel = new JPanel();
sliderPanel = new JPanel();
namePanel = new JPanel();
savePanel = new JPanel();
setTitle("Character Creation Quest");
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,2));
buildPic();
buildSlider();
buildName();
buildSave();
add(picPanel);
add(namePanel);
add(savePanel);
add(sliderPanel);
pack();
setVisible(true);
}//end c'tor
public final void buildPic()
{
//contains image, race, raceLabel, job, jobLabel, genderLabel male, female
String[] raceList = new String[]{"a","b","c"};
String[] jobList = new String[]{"a","b","c"};
image = new JLabel();
race = new JComboBox();
job = new JComboBox();
male = new JRadioButton("Male");
female = new JRadioButton("Female");
picPanel.add(image);
picPanel.add(race);
picPanel.add(job);
picPanel.add(male);
picPanel.add(female);
}//end buildPic
public final void buildSlider()
{
//contains: str, intel, dex, wis, and ptsRemain.
int numSpent = (str.getValue() + intel.getValue()
+ dex.getValue() + wis.getValue());
int numRemain = (100 - numSpent);
String remain;
String spent;
remain = ("Points Remaining: " + numRemain);
spent = ("Points Spent: " + numSpent);
str = new JSlider();
intel = new JSlider();
dex = new JSlider();
wis = new JSlider();
ptsRemain = new JLabel(remain);
ptsSpent = new JLabel(spent);
strLabel = new JLabel("Strength");
intelLabel = new JLabel("Intelligence");
dexLabel = new JLabel("Dexterity");
wisLabel = new JLabel("Wisdom");
sliderPanel.setLayout(new GridLayout(5,2));
sliderPanel.add(ptsRemain);
sliderPanel.add(ptsSpent);
sliderPanel.add(strLabel);
sliderPanel.add(str);
sliderPanel.add(intelLabel);
sliderPanel.add(intel);
sliderPanel.add(dexLabel);
sliderPanel.add(dex);
sliderPanel.add(wisLabel);
sliderPanel.add(wis);
pack();
}//end buildSlider
public final void buildName()
{
//contains: name and namelabel
name = new JTextField(10);
nameLabel = new JLabel();
namePanel.add(name);
}//end buildName
public final void buildSave()
{
//contains: save and load
save = new JButton("Save");
load = new JButton("Load");
TitledBorder title;
title = BorderFactory.createTitledBorder("SHIN");
savePanel.setBorder(title);
savePanel.add(save);
savePanel.add(load);
}//end buildSave
//ignore this for now. get rid of the space above later plz.
public static void main(String[] args) {
new CharacterCreationQuest();
}
}
Your problem is str, intel, dex, and wis is not instantiate yet. Change your buildSlider() method with this code below:
public final void buildSlider()
{
str = new JSlider();
intel = new JSlider();
dex = new JSlider();
wis = new JSlider();
//contains: str, intel, dex, wis, and ptsRemain.
int numSpent = (str.getValue()+intel.getValue()+dex.getValue()+wis.getValue());
int numRemain = (100-numSpent);
String remain;
String spent;
remain = ("Points Remaining: "+numRemain);
spent = ("Points Spent: "+numSpent);
ptsRemain = new JLabel(remain);
ptsSpent = new JLabel(spent);
strLabel = new JLabel("Strength");
intelLabel = new JLabel("Intelligence");
dexLabel = new JLabel("Dexterity");
wisLabel = new JLabel("Wisdom");
sliderPanel.setLayout(new GridLayout(5, 2));
sliderPanel.add(ptsRemain);
sliderPanel.add(ptsSpent);
sliderPanel.add(strLabel);
sliderPanel.add(str);
sliderPanel.add(intelLabel);
sliderPanel.add(intel);
sliderPanel.add(dexLabel);
sliderPanel.add(dex);
sliderPanel.add(wisLabel);
sliderPanel.add(wis);
pack();
}

Swing program exits immediately after starting

The program will launch but then immediately quit. Also, I'm not quite sure if adding multiple panels to a class that extends JFrame is allowed.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TravelExpensesCaskey extends JFrame
{
private double tripDays;
private double airfareCost;
private double carRentalFees;
private double numMiles;
private double parkingFees;
private double taxiCharges;
private double registrationFees;
private double lodgingCost;
private final double FOOD_$_PER_DAY = 37.00;
private final double PARKING_$_PER_DAY = 10.00;
private final double TAXI_$_PER_DAY = 20.00;
private final double LODGING_$_PER_DAY = 95.00;
private final double $_PER_MILE = 0.27;
private JPanel inputPanel;
private JPanel messageBar;
private JPanel panel;
private JPanel calculateBar;
private JButton calcButton;
private final int WINDOW_HEIGHT = 400;
private final int WINDOW_WIDTH = 200;
private JTextField field2;
private JTextField field3;
private JTextField field4;
private JTextField field5;
private JTextField field6;
private JTextField field7;
private JTextField field8;
private JTextField field9;
private double totalExpenditures;
private double totalAllowance;
private double totalBalance;
private double totalStipend;
public TravelExpensesCaskey()
{
setTitle("Travel Expenses");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label1 = new JLabel("Please input the following information about your trip. Enter 0 for any irrelavent values.");
messageBar = new JPanel();
messageBar.add(label1);
add(messageBar);
inputPanel.setLayout(new GridLayout(9,2));
inputPanel = buildPanel();
add(inputPanel);
calculateBar = buildCalculateBar();
add(calculateBar);
setVisible(true);
JOptionPane.showMessageDialog(null, "The total expenses incurred by the business person: " + totalExpenditures + "." +
"\nThe total allowance for the business person: " + totalAllowance + "." +
"\nThe total balance that must be paid for by the business person: " + totalBalance + "." +
"\nThe total stipend available to the business person: " + totalStipend + ".");
}
private JPanel buildPanel()
{
JLabel label2 = new JLabel("Number of Days: ");
JLabel label3 = new JLabel("Airfare Charges: :");
JLabel label4 = new JLabel("Car Rental Fees: ");
JLabel label5 = new JLabel("Number of Miles Driven: ");
JLabel label6 = new JLabel("Amount of Parking Fees: ");
JLabel label7 = new JLabel("Amount of Taxi Charges: ");
JLabel label8 = new JLabel("Conference/Seminar Registration Fees: ");
JLabel label9 = new JLabel("Lodging Charges per Night: ");
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
JPanel panel9 = new JPanel();
panel2.add(label2);
panel3.add(label3);
panel4.add(label4);
panel5.add(label5);
panel6.add(label6);
panel7.add(label7);
panel8.add(label8);
panel9.add(label9);
JTextField field2 = new JTextField(10);
JTextField field3 = new JTextField(10);
JTextField field4 = new JTextField(10);
JTextField field5 = new JTextField(10);
JTextField field6 = new JTextField(10);
JTextField field7 = new JTextField(10);
JTextField field8 = new JTextField(10);
JTextField field9 = new JTextField(10);
panel.add(panel2);
panel.add(field2);
panel.add(panel3);
panel.add(field3);
panel.add(panel4);
panel.add(field4);
panel.add(panel5);
panel.add(field5);
panel.add(panel6);
panel.add(field6);
panel.add(panel7);
panel.add(field7);
panel.add(panel8);
panel.add(field8);
panel.add(panel9);
panel.add(field9);
return panel;
}
private JPanel buildCalculateBar()
{
JPanel panel = new JPanel();
calcButton = new JButton("Calculate");
calcButton.addActionListener(new ButtonListener());
panel.add(calcButton);
return panel;
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String userText = "";
userText = field2.getText();
tripDays = Integer.parseInt(userText);
userText = field3.getText();
airfareCost = Integer.parseInt(userText);
userText = field4.getText();
carRentalFees = Integer.parseInt(userText);
userText = field5.getText();
numMiles = Integer.parseInt(userText);
userText = field6.getText();
parkingFees = Integer.parseInt(userText);
userText = field7.getText();
taxiCharges = Integer.parseInt(userText);
userText = field8.getText();
registrationFees = Integer.parseInt(userText);
userText = field9.getText();
lodgingCost = Integer.parseInt(userText);
calcCharges();
}
}
private void calcCharges()
{
totalExpenditures = (tripDays * lodgingCost) + parkingFees + airfareCost + carRentalFees + taxiCharges + registrationFees;
totalAllowance = (tripDays * FOOD_$_PER_DAY) + (tripDays + PARKING_$_PER_DAY) + (tripDays * TAXI_$_PER_DAY)
+ (tripDays * LODGING_$_PER_DAY) + (numMiles * $_PER_MILE);
if ((totalExpenditures - totalAllowance) < 0)
{
totalStipend = Math.abs(totalExpenditures - totalAllowance);
totalBalance = 0;
}
else if ((totalExpenditures - totalAllowance) > 0)
{
totalBalance = totalExpenditures - totalAllowance;
totalStipend = 0;
}
}
public static void main(String[] args)
{
new TravelExpensesCaskey();
}
}
Your program throw multiple NullPointerExceptions. You declare many objects as class fields and then never initialize them. You need to add at least:
inputPanel = new JPanel(); in constructor,
panel = new JPanel(); in buildPanel();
and in case of all yours JTextFields, change from:
JTextField field = new JTextField();
to:
field = new JTextField();
But it is only beginning because you GUI doesn't display most of components. You need to choose LayoutManager, and work with it. You add all your panels to center of your frames BorderLayout and I think they overlap . So for example, to see your JTextFields, JLabel and JButton, you can change add(component); in constructor for:
add(BorderLayout.NORTH, messageBar);
add(BorderLayout.CENTER, inputPanel);
add(BorderLayout.SOUTH,calculateBar);
also add:
panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS));
in buildPanel() method, and it will look better.
Whats more, you need to move code for JOptionPane to the end of calcCharges() method, this way it will have access to processed date and it will display proper output. At beginning of a app, it displays only zeros.

Attempting to get GUI to cycle through data starting back at the beginning

I am attempting to get the GUI to fully cycle through
but I run into an error after third next button click array element[2]. What I need to do is have the whole thing cycle through when clicking the next button. once it gets to the last iteration of the array will need to go back to the beginning. The thing also is the array is sorted alphabetically to begin with so it would need to start with titles [3] once it has cycled through. Thanks for all the help
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame implements ActionListener {
JButton next;
JButton previous;
JButton first;
JButton last;
private JLabel itmNum = new JLabel("Item Number: ", SwingConstants.RIGHT);
private JTextField itemNumber;
private JLabel proNm = new JLabel ("Product Name: ", SwingConstants.RIGHT);
private JTextField prodName;
private JLabel yr = new JLabel("Year Made: ", SwingConstants.RIGHT);
private JTextField year;
private JLabel unNum = new JLabel("Unit Number: ", SwingConstants.RIGHT);
private JTextField unitNumber;
private JLabel prodPrice = new JLabel("Product Price: ", SwingConstants.RIGHT);
private JTextField price;
private JLabel restkFee = new JLabel("Restocking Fee", SwingConstants.RIGHT);
private JTextField rsFee;
private JLabel prodInValue = new JLabel("Product Inventory Value", SwingConstants.RIGHT);
private JTextField prodValue;
private JLabel totalValue = new JLabel("Total Value of All Products", SwingConstants.RIGHT);
private JTextField tValue;
private double toValue;
Movies[] titles = new Movies[9];
int nb = 0;
public GUI()
{
super ("Inventory Program Part 5");
setSize(800,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
first = new JButton("First");
previous = new JButton("Previous");
next = new JButton("Next");
last = new JButton("Last");
first.addActionListener(this);
previous.addActionListener(this);
next.addActionListener(this);
last.addActionListener(this);
//Movies[] titles = new Movies[9];
titles [0] = new Movies(10001, "King Arthur", 25 , 9.99, 2004, .05);
titles [1] = new Movies(10002,"Tron", 25, 7.99, 1982, .05);
titles [2] = new Movies(10003, "Tron: Legacy",25,24.99,2010,.05);
titles [3] = new Movies(10004,"Braveheart", 25,2.50,1995,.05);
titles [4] = new Movies(10005,"Gladiator",25,2.50,2000,.05);
titles [5] = new Movies(10006,"CaddyShack SE",25,19.99,1980,.05);
titles [6] = new Movies (10007,"Hackers",25,12.50,1995,.05);
titles [7] = new Movies (10008,"Die Hard Trilogy",25,19.99,1988,.05);
titles [8] = new Movies (10009,"Terminator",25,4.99,1984,.05);
Arrays.sort (titles, DVD.prodNameComparator);
itemNumber = new JTextField(Double.toString(titles[3].getitemNum()));
prodName = new JTextField(titles[3].getprodName());
year= new JTextField(Integer.toString(titles[3].getYear()));
unitNumber= new JTextField(Integer.toString(titles[3].getunitNum()));
price= new JTextField(Float.toString(titles[3].getprice()));
rsFee= new JTextField(Double.toString(titles[3].getRestkFee()));
prodValue= new JTextField(Double.toString(titles[3].getprodValue()));
tValue= new JTextField("2636");
nb=0;
next.addActionListener(this);
setLayout(new GridLayout(8,4));
add(itmNum);
add(itemNumber);
add(proNm);
add(prodName);
add(yr);
add(year);
add(unNum);
add(unitNumber);
add(prodPrice);
add(price);
add(restkFee);
add(rsFee);
add(prodInValue);
add(prodValue);
add(totalValue);
add(tValue);
add(first);
add(previous);
add(next);
add(last);
setLookAndFeel();
setVisible(true);
}
public void updateFields()
{
nb++;
itemNumber.setText(Double.toString(titles[nb].getitemNum()));
prodName.setText(titles[nb].getprodName());
year.setText(Integer.toString(titles[nb].getYear()));
unitNumber.setText(Integer.toString(titles[nb].getunitNum()));
price.setText(Double.toString(titles[nb].getprice()));
rsFee.setText(Double.toString(titles[nb].getRestkFee()));
prodValue.setText(Double.toString(titles[nb].getprodValue()));
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if (source == next)
{
if (titles[nb]== titles[8])
{
titles[nb] = titles[0];
}
else {
nb++;
}
updateFields();
}
}
private void setLookAndFeel()
{
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println("couln't use the system"+ "look and feel: " + e);
}
}
}
The reason you are advancing so quickly through the records is that you have added your ActionListener to your next JButton twice:
next.addActionListener(this);
This, in turn, increments your record index (nb) in the ActionListener as well as in your updateFields method. Remove this increment from one of these locations.
Also, when you check if you've reached the last title, you never reset your record index nb. You could do:
if (titles[nb] == titles[8]) {
nb = 0;
...

Categories