Main method's New Instance ignored [duplicate] - java

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

Related

The reason why I cannot find the value that I enter first from JTextField

Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
class Phone{
private String name;
private String phone_number;
private String address;
public Phone(String name,String phone_number, String address) {
this.name = name;
this.phone_number = phone_number;
this.address = address;
}
String getName() {return this.name;}
String getNumber() {return this.phone_number;}
String getAddress() {return this.address;}
}
public class Phone_Book extends JFrame{
private JTextArea ta = new JTextArea();
private JButton lookup = new JButton("lookup");
private JButton search = new JButton("search");
private JButton input = new JButton("input");
private JButton remove = new JButton("remove");
private JLabel name = new JLabel("name");
private JLabel phone_number = new JLabel("phone_number");
private JLabel address = new JLabel("address");
private JTextField name_input = new JTextField();
private JTextField phone_number_input = new JTextField();
private JTextField address_input = new JTextField();
private HashMap<String,Phone> hashPhoneBook = new HashMap<String, Phone>();
public Phone_Book() {
setTitle("Phone Book");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(null);
//*********************PhoneBook Design ********************************************
JPanel buttonPanel = new JPanel();
buttonPanel.add(inquiry);
buttonPanel.add(search);
buttonPanel.add(input);
buttonPanel.add(remove);
buttonPanel.setLayout(new GridLayout(1,4));
buttonPanel.setSize(350,30);
buttonPanel.setLocation(670,70);
JPanel labelPanel = new JPanel();
labelPanel.add(name);
labelPanel.add(phone_number);
labelPanel.add(address);
labelPanel.setLayout(new GridLayout(3,1));
labelPanel.setSize(80,150);
labelPanel.setLocation(670,110);
JPanel textPanel = new JPanel();
textPanel.add(name_input);
textPanel.add(phone_number_input);
textPanel.add(address_input);
textPanel.setLayout(new GridLayout(3,1,0,25));
textPanel.setSize(260, 140);
textPanel.setLocation(750, 120);
JScrollPane js = new JScrollPane(ta);
js.setSize(600, 300);
js.setLocation(20, 10);
c.add(js);
c.add(buttonPanel);
c.add(labelPanel);
c.add(textPanel);
//********************** PhoneBook Function **************************************************
...
//---- problem occurs-------------------------------------
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ta.setText(" ");
Phone p = hashPhoneBook.get(name_input.getText());
if(p == null) ta.append(name_input.getText()+"doesn't exist\n");
else {
ta.append(p.getName()+" "+p.getNumber()+" "+p.getAddress()+"\n");
}
name_input.setText(" ");
}
});
//------------------------------------------------------
...
setSize(1100,400);
setVisible(true);
}
public static void main(String[] args) {
new Phone_Book();
}
}
Here is the problem.
I can see all values (including a first value that I first entered after running a program) when I click the 'lookup'button (I thought it isn't needed, I didn't put it in this code).
When I try to find or remove the first value from HashMap, it didn't work.
Only I got the 'null'
But, when I pressed the 'space' and entered the value, it worked well.
(for example, 'David' -----> ' David')
I wonder why this is happening?
It seems like the keys in your HashMap are not set up right. You haven't included the code where this is set.
IMO though, I'd implement the phone book with a simple line delimited text file & load all records in a string instead of using a HashMap for your phone book. The reason being that you can then use regular expressions to match case-insensitive and partial records. Using a HashMap, the key must be an exact match

Java Swing Eclipse Program seems to compile; Wont run however

ive recently just got back into programming Swing and java in general and am quite rusty. My program im trying to finish is seeming to compile going by eclipse, but it wont run, its telling me it doesn't have a main type. And its not giving me an error notifications so im kind of stuck here at the moment.
I've never seen this error before so not sure what it is, or cant remember what it is if I have. Any ideas what im doing wrong or should fix to get this to run, thanks:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.Timer;
import javax.swing.Timer.*;
import javax.swing.event.*;
public class FamousLocations extends JFrame implements ChangeListener, ActionListener, Runnable
{
private static final long serialVersionUID = 0;
JMenuBar p = new JMenuBar();
int Selected = 0;
ImageIcon a = new ImageIcon("america.jpg");
ImageIcon j = new ImageIcon("Japan.jpg");
ImageIcon c = new ImageIcon("china.jpg");
ImageIcon i = new ImageIcon("ireland.jpg");
ImageIcon t = new ImageIcon("thailand.jpg");
ImageIcon ca = new ImageIcon("Niagra-Falls.jpg");
Icon[] pics = {a,j,c,i,t,ca};
private JLabel ImageLabel = new JLabel(pics[Selected]);
String america = ("Grand Canyon, America");
String japan = ("Kinkaku-ji (The Golden Pavilion) Kyoto, Japan");
String china = ("Mount Huangshan, China");
String ireland = ("Newgrange, Ireland");
String thailand = ("Bangkok ,Thailand");
String canada = ("Niagra Falls , Canada");
String[] Box = {america, japan, china, ireland, thailand, canada};
JTextArea lo = new JTextArea(Box[Selected]);
String InfoGrand = new String ("desciption");
String InfoHiro = new String ("desciption");
String InfoMount = new String ("desciption");
String InfoNew = new String ("desciption");
String InfoBang = new String ("desciption");
String InfoNiag = new String ("desciption");
String[] Info = {InfoGrand, InfoHiro, InfoMount, InfoNew, InfoBang, InfoNiag};
JTextArea ta = new JTextArea(Info[Selected]);
private JTabbedPane tp = new JTabbedPane();
public JSlider slider = new JSlider();
private JPanel dropd = new JPanel();
private JPanel checkb = new JPanel();
private JPanel ImagePan = new JPanel();
private JPanel InfoPan = new JPanel();
private JCheckBox slider1 = new JCheckBox ("Show Slider" , true);
private JCheckBox slideshow1 = new JCheckBox ("Slideshow", false);
JComboBox com1 = new JComboBox(Box);
public FamousLocations(){
setTitle("My Bucket List");
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.white);
getContentPane().setSize(1000,1000);
getContentPane().add(dropd);
getContentPane().add(slider,BorderLayout.SOUTH);
getContentPane().add(slider1);
getContentPane().add(slideshow1);
getContentPane().add(tp);
slider.setValue(0);
slider.addChangeListener(this);
slider.setOrientation(JSlider.HORIZONTAL);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMajorTickSpacing(1);
slider.setMaximum(5);
slider.setSnapToTicks(true);
ImagePan.add(ImageLabel);
checkb.add(com1);
checkb.add(slider1);
checkb.add(slideshow1);
tp.addTab("Photo", ImagePan);
tp.addTab("Description of Area", InfoPan);
tp.addTab("Index and Options", checkb);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setVisible(true);
ta.setSize(400,400);
slider1.setVisible(true);
slider1.addActionListener(this);
slideshow1.setVisible(true);
slideshow1.addActionListener(this);
com1.addActionListener(this);
com1.addActionListener(this);
JMenu help = new JMenu("HELP");
JMenuItem AL1 = help.add("how to use");
JMenuItem AL2 = help.add("EXIT");
p.add(help);
this.setJMenuBar(p);
AL1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null,"error");
}
});
AL2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
setSize(250,250);
setVisible(true);
}
public void change(){
JTextArea ta=new JTextArea(Box[Selected]);
ImagePan.removeAll();
ImagePan.add(ImageLabel=new JLabel(pics[Selected]));
InfoPan.removeAll();
InfoPan.add(ImageLabel=new JLabel(Info[Selected]));
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setVisible(true);
ta.setSize(400,400);
ImagePan.repaint();
validateTree();
}
public void run(){
for(int y = 0;y==y+1; y++){
slider.setValue(y);
try{
Thread.sleep (1000);
}
catch (Exception e) {}
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==slider1) {slider.setVisible(slider1.isSelected());}
else if(e.getSource()==com1)
{Selected=com1.getSelectedIndex(); change();}
else if(e.getSource()==slideshow1)
{new Thread(this).start(); }
}
public void stateChanged(ChangeEvent e) {
if(e.getSource()==slider){Selected=slider.getValue();change();}
}
}

Java: Action Handler

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.

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.

Problems with Layout for Login GUI

I am trying to make a simple GUI that has the username and password with the textfields under each one.
Any help would be greatly appreciated!
Here is my code. I cannot figure out how to get everything in it's rightful place.
enter code here
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import java.awt.*;
import javax.swing.*;
/**
*/
public class PassWordFrame extends JFrame
{
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 400;
private JLabel instruct;
private JLabel username;
private JLabel password;
private JTextField usertext;
private JTextField passtext;
private JButton login;
private ActionListener listener;
String text = "";
public PassWordFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
listener = new ClickListener();
}
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.out.println("Hello");
}
}
public void createComponents()
{
Color blue = new Color(0,128,155);
Font font = new Font("Times New Roman", Font.BOLD, 14);
instruct = new JLabel("Please enter your username and password.");
instruct.setFont(font);
username = new JLabel("Username: ");
username.setFont(font);
password = new JLabel("Password: ");
password.setFont(font);
usertext = new JTextField(FIELD_WIDTH);
passtext = new JTextField(FIELD_WIDTH);
login = new JButton("Login");
login.setFont(font);
instruct.setForeground(Color.BLACK);
login.setForeground(Color.BLACK);
username.setForeground(Color.BLACK);
password.setForeground(Color.BLACK);
login.addActionListener(listener);
JPanel panel = new JPanel();
panel.setBackground(blue);
panel.add(instruct);
panel.add(username);
panel.add(usertext);
panel.add(password);
panel.add(passtext);
panel.add(login);
add(panel);
}
}
Change the line where you create the panel to
JPanel panel = new JPanel(new GridLayout(2,2));

Categories