Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do I pass an instance of an object to a different object

 
Darren Wilkinson
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a class ApplicationGui2 (ag) which creates an instance of MyTableModel2 (mtm)

MyTableModel2 has all the methods required to create instances of the class RecordData (rd)

The user uses a modal dialog which instantiates an instance of class NewRecordInput (nri)

nri gathers the user data and then needs to pass this data (stored as a String[]) to the mtm method createNewRecord() which creates a new instance of class RecordData and stores this object in mtm's Vector

What I want to do is; pass a reference to mtm, from ag to nri, so that nri can call mtm.createNewRecord() but my attempts so far produce a NullPointerException

Can anyone help ???
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
change the constructor for NewRecordInput() from this

public NewRecordInput(MyTableModel2 testTableModel)
{
MyTableModel2 tempTableModel = new MyTableModel2();
tempTableModel = testTableModel;
...
}

to this

MyTableModel2 tempTableModel;//<---moved to here
public NewRecordInput(MyTableModel2 testTableModel)
{
//MyTableModel2 tempTableModel = new MyTableModel2();//<----remove line
tempTableModel = testTableModel;
...
}

this should get rid of your NPE.
Don't know if it will get you the funcionality you want.

You may also want to add this line to the constructor for ApplicationGui2

setDefaultCloseOperation(EXIT_ON_CLOSE);
 
Darren Wilkinson
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you :-)

My question is: why does this work and my code not work. I am having trouble following the reason for this.

Could you explain please.

Thank you.

By the way, this isn't a homework assignment. I am studying towards the J2SE Programmers certification but on my own using Mughal & Rasmussens' Guide to Java Certification... oh and the WhizLabs exam sim.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Declaring 'MyTableModel2 tempTableModel' within the constructor makes
tempTableModel local to the constructor only, but access to tempTableModel is
required from setUserInput()
 
Darren Wilkinson
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you :-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic