java.lang.NullPointerException

java.lang.NullPointerException

Page 1 of 1

9 Replies - 13815 Views - Last Post: 18 June 2007 - 01:04 AM Rate Topic: -----

#1 princejlynn  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 79
  • Joined: 15-January 07

java.lang.NullPointerException

Post icon  Posted 16 June 2007 - 12:57 PM

[quote]
Can anyone help me with this exception? I have the program compiling, but when I execute, I get the below error. It tells me that the applet is not initialized, and I can't see anything. Please help.



java.lang.NullPointerException



 * Purpose:		Write the program in Java (with a graphical user interface) and have it 
 *				calculate and display the mortgage payment amount from user input of the
 *				amount of the mortgage and the user's selection from a menu of available mortgage loans: 

				- 7 years at 5.35%
				- 15 years at 5.5%
				- 30 years at 5.75%

				Use an array for the mortgage data for the different loans. Display the mortgage 
				payment amount followed by the loan balance and interest paid for each payment over 
				the term of the loan. Allow the user to loop back and enter a new amount and make a 
				new selection or quit. Please insert comments in the program to document the program. 
 */
 

//packages imported for class and method use 
import java.applet.Applet;
import java.awt.*;
import java.awt.Font;
import java.text.DecimalFormat;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JComboBox;
import java.applet.Applet;
import java.awt.*;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import java.awt.Button;


//Begin Program
public class JennProject extends JApplet implements ActionListener, ItemListener{
	
	TextField principalText, paymentText, termText, interestText, scrollText, interestPaidText, balancePaidText;

	  JButton calculateButton; //calculation button
	  JButton clear; //clear screen button
	  JButton exit; //exit program button
	  JButton amortize; //amortize loan button
  
	  String[] items = { "7 Years at 5.35%" , "15 Years at 5.50%", "30 Years at 5.75%"};
	  int[] termarray = {7, 15, 30};
	double[] interestarray = {5.35, 5.50, 5.75};
	int i = 0;
	double principal = 0;
	int term = 0;
	double interest = 0;
	double payment = 0;
	double balancePaid = 0;
	double interestPaid = 0;
	JTextArea scrollPane = new JTextArea(12,50);
	JScrollPane scrollBar = new JScrollPane(scrollPane);



	//DecimalFormat yearform = new DecimalFormat("##"); //Year Format
	//DecimalFormat intform = new DecimalFormat("#,##0.00"); //Percentage Format
	//DecimalFormat intPlaces = new DecimalFormat("000\t");
	
	String numberformat = "######";
	String percentformat = "###.###%";
	
	NumberFormat format;
	
	NumberFormat currency = NumberFormat.getCurrencyInstance();

	NumberFormat nodecimals = new DecimalFormat(numberformat);

	NumberFormat percentdecimals = new DecimalFormat(percentformat);
	
	  Object oldItem;
	
	Label heading = new Label("Mortgage Calculator");
	Font bigFont = new Font("TimesRoman", Font.BOLD, 24);
	
	public void init() {
		
		heading.setFont(bigFont);
		
 		// Use a grid bag layout.
		GridBagLayout layout = new GridBagLayout();
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.fill = GridBagConstraints.HORIZONTAL;

		
		setBackground(Color.blue); // Set background color to blue
		setForeground(Color.white);  // Set foreground color to white
		setLayout(layout);
		setVisible(true);

		


		Label principalLabel = new Label("Principal");
		Label termLabel = new Label("Years");
		Label interestLabel = new Label("Interest Rate");
		Label paymentLabel = new Label("Monthly Payments");
		
		
		//Set field lengths
		principalText = new TextField(10);
		principalText.requestFocus();
		termText = new TextField(10);
		paymentText = new TextField(10);
		interestText = new TextField(10);
		
		//Display payment field/not editable
		paymentText.setEditable(false);

		calculateButton = new JButton("Calculate");
		clear = new JButton("Clear");
		exit = new JButton("Exit");
		amortize = new JButton("Amortize");
		
		//defining combobox
		JComboBox cb = new JComboBox(items);
		
		//Get current value of combobox
		Object obj = cb.getSelectedItem();
		
		//set a new value for combobox
		cb.setSelectedItem("7 Years at 5.35%");
		obj = cb.getSelectedItem();
		
		cb.setSelectedItem("15 Years at 5.50%");
		obj = cb.getSelectedItem();
		
		cb.setSelectedItem("30 Years at 5.75%");
		obj = cb.getSelectedItem();
		
		//Get number of items
		int num = cb.getItemCount();
		
		//Get items
		for (int i=0; i<num; i++){
			Object item = cb.getItemAt(i);
		}
		   	
		// Define the grid bag
		constraints.weighty = 1.0;//Distribute space of 1.0
		constraints.gridwidth = GridBagConstraints.REMAINDER;//last component
		constraints.anchor = GridBagConstraints.WEST;//top of display/centered horizontally
		layout.setConstraints(heading, constraints);

		// Anchor most components to the left
		constraints.anchor = GridBagConstraints.WEST;

		//Setting constraints
		constraints.gridwidth = GridBagConstraints.RELATIVE;//place next to last component
		layout.setConstraints(principalLabel, constraints);
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		layout.setConstraints(principalText, constraints);

		constraints.gridwidth = GridBagConstraints.RELATIVE;//place next to last component
		layout.setConstraints(termLabel, constraints);
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		layout.setConstraints(termText, constraints);

		constraints.gridwidth = GridBagConstraints.RELATIVE;//place next to last component
		layout.setConstraints(interestLabel, constraints);
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		layout.setConstraints(interestText, constraints);

		constraints.gridwidth = GridBagConstraints.RELATIVE;//place next to last component
		layout.setConstraints(paymentLabel, constraints);
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		layout.setConstraints(paymentText, constraints);

		constraints.anchor = GridBagConstraints.EAST;
		layout.setConstraints(cb, constraints);
		
		constraints.anchor = GridBagConstraints.CENTER;
		layout.setConstraints(clear, constraints);
		
		constraints.anchor = GridBagConstraints.CENTER;
		layout.setConstraints(exit, constraints);
		
		constraints.anchor = GridBagConstraints.CENTER;
		layout.setConstraints(amortize, constraints);
			
		constraints.anchor = GridBagConstraints.WEST;
		layout.setConstraints(calculateButton, constraints);
		
		scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));


  
		// Add components
		add(heading);
		add(principalLabel);
		add(interestPaidText);
		add(balancePaidText);
		add(principalText);
		add(termLabel);
		add(termText);
		add(interestLabel);
		add(interestText);
		add(paymentLabel);
		add(paymentText);
		add(calculateButton);
	   	add(clear);
		add(exit);
		add(amortize);
		add(cb);
		add(scrollPane);

		

		// Receive action events
		JennProject actionListener = new JennProject();
		principalText.addActionListener(this);
		termText.addActionListener(this);
		interestText.addActionListener(this);
		calculateButton.addActionListener(this);
		clear.addActionListener(this);
		exit.addActionListener(this);
		amortize.addActionListener(this);
		cb.addActionListener(this);
		cb.addItemListener(this);
		setVisible(true);	
		
	
		// Number formatting
		format = NumberFormat.getInstance();
		format.setMinimumFractionDigits(2);
		format.setMaximumFractionDigits(2);
	   
  }
  
	public void itemStateChanged(ItemEvent evt) {
			JComboBox cb = (JComboBox)evt.getSource();
	
			// Get the affected item
			Object item = evt.getItem();
	
			if (evt.getStateChange() == ItemEvent.SELECTED) {
				// Item was just selected
			} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
				// Item is no longer selected
			}
			
		}
	
			
  //User presses calculate
	  public void actionPerformed(ActionEvent evt) {
		  JComboBox cb = (JComboBox)evt.getSource();
		Object newItem = cb.getSelectedItem();
		boolean same = newItem.equals(oldItem);
		oldItem = newItem;
	
   		if ("comboBoxEdited".equals(evt.getActionCommand())) {
   			}else if ("comboBoxChanged".equals(evt.getActionCommand())){
   			}
			
   		int iTerm;
   		int iTerm1;
   		int iTerm2;
   		double iinterest;
   		double iinterest1;
   		double iinterest2;
   
   		iTerm = termarray[0];
   		iTerm1 = termarray[1];
   		iTerm2 = termarray[2];
   		iinterest = interestarray[0];
   		iinterest1 = interestarray[1];
   		iinterest2 = interestarray[2];

   		if (newItem == "7 Years at 5.35%"){
   			termText.setText(Integer.toString(iTerm));
   			interestText.setText(Double.toString(iinterest));
   		} else if (newItem == "15 Years at 5.50%"){
   			termText.setText(Integer.toString(iTerm1));
   			interestText.setText(Double.toString(iinterest1));
   		} else if (newItem == "30 Years at 5.75%"){
   			termText.setText(Integer.toString(iTerm2));
   			interestText.setText(Double.toString(iinterest2));
   		}
   		
   	String ErrorMessage = "";
   	boolean TrueorFalseError = false;	
   	Object cmd = evt.getSource();
   	//double result = 0.0;
   	//result = calculate();
	//paymentText.setText(format.format(result));
		
   		
 		if (cmd.equals(calculateButton))
 			{
				try
				{
					principal = Double.parseDouble(principalText.getText());
					term = Integer.parseInt(termText.getText());
					interest = Double.parseDouble(interestText.getText());
					
				}
				//showStatus("");
				catch (NumberFormatException exc)
				{
					ErrorMessage = ErrorMessage + "Please Enter Numeric Values.\n";
					
					TrueorFalseError = true;
					
				}
				
					String principalString = principalText.getText();
					String termString = termText.getText();
					String interestString = interestText.getText();

   				if (principalString.length() != 0 && termString.length() != 0 && interestString.length() != 0)
   				{
   					ErrorMessage = ErrorMessage + "Fields may not be blank or contain a zero.\n";
   					
   					TrueorFalseError = true;
   				}
   				
   				if (TrueorFalseError = true)
   					
   				{
   					showStatus("Warning");
   					paymentText.setText("");
   				}

	 			else
	 				
	 			{
	
				  payment = (principal*interest*01)/(1-Math.pow(1+ interest, -term));
				  balancePaid = payment*term;
				  interestPaid = balancePaid - principal;
				  
				  paymentText.setText
					  (format.format(payment));
					  
				  balancePaidText.setText
					  (format.format(balancePaid));
					  
				  interestPaidText.setText
					  (format.format(interestPaid));
					  
				  calculateButton.setEnabled(true);
				  
				}
				
 			}
 			
 			if(cmd.equals(amortize))
 				
 			{
 				double thismonthinterest = 0;
				double thismonthprincipal = 0;
				double thismonthtotaldue = 0;
				double monthlyinterestrate = 0;

				String Title =" Payment\tPrincipal\tInterest\tBalance\n";


				thismonthtotaldue = (interest / 100) / 12;

				thismonthtotaldue = principal;


				// Setup header for TextArea

				scrollText.setText(Title);


				for(int i = 0; i <= term - 1; i++)

{



				thismonthinterest = thismonthtotaldue * monthlyinterestrate;


				if(thismonthinterest <= 0)

				thismonthinterest = 0;


				thismonthprincipal = payment - thismonthinterest;

				thismonthtotaldue = thismonthtotaldue - thismonthprincipal;


				scrollPane.append(nodecimals.format(i + 1) + "\t" + currency.format(thismonthprincipal) + "\t"
					+ percentdecimals.format(thismonthinterest) + "\t" + currency.format(thismonthtotaldue) + "\n");


				// This positions the cursor to the top of the textArea. Otherwise, the

				// textArea would be displayed showing the bottom rows.

				scrollPane.setCaretPosition(0);

				}

			
  
	 		if(cmd == exit)
	 			
	 		{
	 		
			System.exit(0);
 			}
	  }
		
}
}
//End program



Is This A Good Question/Topic? 0
  • +

Replies To: java.lang.NullPointerException

#2 PennyBoki  Icon User is offline

  • system("revolution");
  • member icon

Reputation: 53
  • View blog
  • Posts: 2,334
  • Joined: 11-December 06

Re: java.lang.NullPointerException

Posted 16 June 2007 - 01:53 PM

the code is huge, but a null pointer exception is given when 'you' call for an object but that object is null i.e. is not initialized, so my suggestion would be to look in the init() method, I commented out the line
//JennProject actionListener = new JennProject();

and still have the same problem but this time the label Mortgage Calculator was shown ...
Was This Post Helpful? 0
  • +
  • -

#3 princejlynn  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 79
  • Joined: 15-January 07

Re: java.lang.NullPointerException

Posted 16 June 2007 - 03:24 PM

View PostPennyBoki, on 16 Jun, 2007 - 01:53 PM, said:

the code is huge, but a null pointer exception is given when 'you' call for an object but that object is null i.e. is not initialized, so my suggestion would be to look in the init() method, I commented out the line
//JennProject actionListener = new JennProject();

and still have the same problem but this time the label Mortgage Calculator was shown ...


Thanks I was able to fix that, but now I am getting this:

Exception in thread "AWT-EventQueue-1" java.lang.ClassCastException: java.awt.TextField cannot be cast to javax.swing.JComboBox


I guess I am not supposed to have AWT and SWING together.

[quote]
Was This Post Helpful? 0
  • +
  • -

#4 GWatt  Icon User is online

  • member icon

Reputation: 270
  • View blog
  • Posts: 3,068
  • Joined: 01-December 05

Re: java.lang.NullPointerException

Posted 16 June 2007 - 05:09 PM

You are allowed to run Swing and AWT together all you want, but you are trying to make a textfield into a combobox. It would be like trying to make a String into a Integer.
Was This Post Helpful? 0
  • +
  • -

#5 princejlynn  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 79
  • Joined: 15-January 07

Re: java.lang.NullPointerException

Posted 17 June 2007 - 12:58 PM

[quote name='princejlynn' date='16 Jun, 2007 - 03:24 PM' post='231865']

View PostPennyBoki, on 16 Jun, 2007 - 01:53 PM, said:

the code is huge, but a null pointer exception is given when 'you' call for an object but that object is null i.e. is not initialized, so my suggestion would be to look in the init() method, I commented out the line
//JennProject actionListener = new JennProject();

and still have the same problem but this time the label Mortgage Calculator was shown ...


Thanks I was able to fix that, but now I am getting this:

Exception in thread "AWT-EventQueue-1" java.lang.ClassCastException: java.awt.TextField cannot be cast to javax.swing.JComboBox


I guess I am not supposed to have AWT and SWING together.

Quote

Any suggestions on how to fix this? Could you show me the piece, that is creating a problem, and suggest how to get around it? Please help, this is due tomorrow. Thanks

Was This Post Helpful? 0
  • +
  • -

#6 PennyBoki  Icon User is offline

  • system("revolution");
  • member icon

Reputation: 53
  • View blog
  • Posts: 2,334
  • Joined: 11-December 06

Re: java.lang.NullPointerException

Posted 17 June 2007 - 02:10 PM

Why do you do this, in itemStateChanged(ItemEvent evt)

Quote

JComboBox cb = (JComboBox)evt.getSource();

// Get the affected item
Object item = evt.getItem();

and about your error
just as GWatt said you are trying to cast a TextField into JComboBox. Look through you casting very thoroughly ...
Was This Post Helpful? 0
  • +
  • -

#7 princejlynn  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 79
  • Joined: 15-January 07

Re: java.lang.NullPointerException

Posted 17 June 2007 - 02:40 PM

View PostPennyBoki, on 17 Jun, 2007 - 02:10 PM, said:

Why do you do this, in itemStateChanged(ItemEvent evt)

Quote

JComboBox cb = (JComboBox)evt.getSource();

// Get the affected item
Object item = evt.getItem();

and about your error
just as GWatt said you are trying to cast a TextField into JComboBox. Look through you casting very thoroughly ...

Quote

To be honest, I was using an example to help me create that portion. However, it is used to determing when something is deselected and something new is selected. Is it creating a problem?? I am currently going through the code again to find out where I cast a textfield into the combobox. I have so far been unsucessful. Thanks.

Was This Post Helpful? 0
  • +
  • -

#8 PennyBoki  Icon User is offline

  • system("revolution");
  • member icon

Reputation: 53
  • View blog
  • Posts: 2,334
  • Joined: 11-December 06

Re: java.lang.NullPointerException

Posted 17 June 2007 - 02:45 PM

You are using the evt event as far as I can see to determine if something is selected or not, so I see no reason for those lines of code I marked
Was This Post Helpful? 0
  • +
  • -

#9 princejlynn  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 79
  • Joined: 15-January 07

Re: java.lang.NullPointerException

Posted 17 June 2007 - 08:23 PM

[quote name='princejlynn' date='17 Jun, 2007 - 02:40 PM' post='232057']

View PostPennyBoki, on 17 Jun, 2007 - 02:10 PM, said:

Why do you do this, in itemStateChanged(ItemEvent evt)

Quote

JComboBox cb = (JComboBox)evt.getSource();

// Get the affected item
Object item = evt.getItem();

and about your error
just as GWatt said you are trying to cast a TextField into JComboBox. Look through you casting very thoroughly ...

Quote

To be honest, I was using an example to help me create that portion. However, it is used to determing when something is deselected and something new is selected. Is it creating a problem?? I am currently going through the code again to find out where I cast a textfield into the combobox. I have so far been unsucessful. Thanks.

Quote

Ok, I have commented that out, and I think you were right, it was unnecessary and didn't affect anything. I uncommented everything, and have it compiling again, but could not find the textfield to combobox problem. And, now that I uncommented, ect. the error has changed:

Exception in thread "AWT-EventQueue-1" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JComboBox
at JennProject.actionPerformed(JennProject.java:305)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)


Line 305 is this:

JComboBox cb = (JComboBox)evt.getSource();

Any more suggestions??

Was This Post Helpful? 0
  • +
  • -

#10 PennyBoki  Icon User is offline

  • system("revolution");
  • member icon

Reputation: 53
  • View blog
  • Posts: 2,334
  • Joined: 11-December 06

Re: java.lang.NullPointerException

Posted 18 June 2007 - 01:04 AM

Show me the code again to see what you have so far
and try with commenting out that line 305.
Was This Post Helpful? 2

Page 1 of 1