jkteater
asked on
getting values from combo box
I have 3 combo boxes in my dialog.  They are populated with  user names.  I am trying to write a method to get the value from one combo box so I can pass it to a different class.  I am having no luck getting the value.  Does it have to be in a Action in order to get the value?
I have tried this
 Object s1 = keyUserComboBox.getSelecte dItem(); <== Throwing a null pointer
I have tried this
public String getKeyUserSelect(){
Object s1 = keyUserComboBox.getSelectedItem();
String ku = s1.toString();
return ku;
}
 Object s1 = keyUserComboBox.getSelecte
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
If it is still null at that point - you'll get NPE
Even when the combo is initialized, you need to be careful of an NPE:
Object s1 = keyUserComboBox.getSelectedItem();
return s1 == null? null : s1.toString();
>Does it have to be in a Action in order to get the value?
No, it dioes not need to be in Action, but the combobox needs to be created
before you try to get selection from it.
So it is normal practice that it would be done in Action - but you saw for yourslef alraedy taht we can
extract the selection from combobox even from the code of the different class.
The main thisn is that instance of combobox should exist and should be populated at the moment you try to get selection
ASKER
I am trying to get the value with a button created in the same dialog as the combo boxes. Â So it should have a value when clicked.
You can check - printout before that statement:
System.out.println( "combobox "Â + keyUserComboBox);
If it is null then iit is not initialized
System.out.println( "combobox "Â + keyUserComboBox);
If it is null then iit is not initialized
better this way:
public String getKeyUserSelect(){
if(keyUserComboBox == null)System.out.prtnln("combobox is null");
Object s1 = keyUserComboBox.getSelectedItem();
if(s1 == null)System.out.prtnln("s1 is null");
String ku = s1.toString();
return ku;
}
ASKER
Yep it is null
So check how it could have happened.
>I am trying to get the value with a button created in the same dialog as the combo boxes
do you mean that you are doing it in the action method associated with the button?
>I am trying to get the value with a button created in the same dialog as the combo boxes
do you mean that you are doing it in the action method associated with the button?
You normally create all elemnts in constructore and get data from them in the action or event handlers methods - so they alredy exist by that time
ASKER
This is going to sound very strange, but coming from me - it may not.
My combo boxes and my send Button are in my RequestTransmittalDialog class.
The actual listener for the button is in my SingletonSelectTable class
the method the listener is calling is in my EdiBaseDialog class
So the RequestTransmittalDialog opens, the user selects a KeyUser, AME, PME and then clicks the Send Button
That is running a method called buildXML() in my EdiBaseClass. Â There is a part of the XML that needs the values from KeyUser, AME, PME.
So I guess even though I can see the values of the combo box, it is not  instantiated when I am calling the method from  EdiBaseDialog
My combo boxes and my send Button are in my RequestTransmittalDialog class.
The actual listener for the button is in my SingletonSelectTable class
the method the listener is calling is in my EdiBaseDialog class
So the RequestTransmittalDialog opens, the user selects a KeyUser, AME, PME and then clicks the Send Button
That is running a method called buildXML() in my EdiBaseClass. Â There is a part of the XML that needs the values from KeyUser, AME, PME.
So I guess even though I can see the values of the combo box, it is not  instantiated when I am calling the method from  EdiBaseDialog
ASKER
I am pretty sure that the problem is keyUserComboBox is not instantiated and that is what it causing the NPE
If you see the box - then it is instantiated - the problem is mots probably that you do not pass the reference to it correctly form one of yopur classes to another
ASKER
I was afraid you where going to say that.
ASKER
In the method in my EdiBaseDialog I am doing
RequestTransmittalDialog rtd = new RequestTransmittalDialog() ;
String key = rtd.getKeyUserSelect();
The constructor in RequestTransmittalDialog
public RequestTransmittalDialog() {
              Â
  }  // end constructor
RequestTransmittalDialog rtd = new RequestTransmittalDialog()
String key = rtd.getKeyUserSelect();
The constructor in RequestTransmittalDialog
public RequestTransmittalDialog()
              Â
  }  // end constructor
Your snippet does not say mauch
what mans thsi:
public RequestTransmittalDialog() {
              Â
  }  //
do you create your combobox in the constructor of RequestTransmittalDialog ?
what mans thsi:
public RequestTransmittalDialog()
              Â
  }  //
do you create your combobox in the constructor of RequestTransmittalDialog ?
ASKER
No the combo box is not created in the constructor - it is created in a method
private JPanel createUserPanel(EdiGetRequ estTransmi ttalInfoOp eration.Tr ansmittalI nfo info) {
   keyUserModel = new MyListModel(info.keyUserId s);
   keyUserComboBox = new JComboBox(keyUserModel);
   keyUserComboBox.setPreferr edSize(key UserComboB ox.getPref erredSize( ));
   keyUserModel.setSelectedIt em(keyUser Model.id2N ame(sessio n.getCrede ntials().g etUserName ()));
   keyUserComboBox.setModel(k eyUserMode l);
private JPanel createUserPanel(EdiGetRequ
   keyUserModel = new MyListModel(info.keyUserId
   keyUserComboBox = new JComboBox(keyUserModel);
   keyUserComboBox.setPreferr
   keyUserModel.setSelectedIt
   keyUserComboBox.setModel(k
ASKER
public class RequestTransmittalDialog extends JDialog implements ItemListener {
   JComboBox         keyUserComboBox;
Â
   JComboBox         keyUserComboBox;
Â
Is this method called form the construtor?
RequestTransmittalDialog rtd = new RequestTransmittalDialog()
String key = rtd.getKeyUserSelect();
ASKER
constructor calls createDialog();
then in the createDialog method the  createUserPanel method is called.
then in the createDialog method the  createUserPanel method is called.
ASKER
I created a second constructor with nothing in it because I did not want to pass in all the stuff of the first one
First constructor
public RequestTransmittalDialog(E diGetReque stTransmit talInfoOpe ration.Tra nsmittalIn fo info, List workItems,
     EdiProject currentProject, Dialog parent, TCSession theSession, Registry theRegistry) {
   super(parent, true);
   session = theSession;
   appReg = theRegistry;
   project = currentProject;
   myModel = SingletonSelectTable.getIn stance();
   sendReqButton = myModel.getSendReqButton() ;
   createDialog(info);
   // ircw.setList(workItems);
  } // end constructor
 Â
second one
public RequestTransmittalDialog() {
  Â
             Â
  }  // end constru
First constructor
public RequestTransmittalDialog(E
     EdiProject currentProject, Dialog parent, TCSession theSession, Registry theRegistry) {
   super(parent, true);
   session = theSession;
   appReg = theRegistry;
   project = currentProject;
   myModel = SingletonSelectTable.getIn
   sendReqButton = myModel.getSendReqButton()
   createDialog(info);
   // ircw.setList(workItems);
  } // end constructor
 Â
second one
public RequestTransmittalDialog()
  Â
             Â
  }  // end constru
ASKER
I think I understand now - my constructor was doing nothing
So how can you create another instance (with nothing in it) and want to get from it the same combobox you are seeing on your screen?
Do you rememeber my example with my hat which you want to paint red and then buy brand new hat and apint it and then look at mine and wondering why is it not red?
You are again doing the same thing. You gave everything to that first instance. Now you create this mnew instance which has nkothing
has nothing to do with the oprevious instance and wwant to get for it something which is a part of the first instance - makes no sense.
Do you rememeber my example with my hat which you want to paint red and then buy brand new hat and apint it and then look at mine and wondering why is it not red?
You are again doing the same thing. You gave everything to that first instance. Now you create this mnew instance which has nkothing
has nothing to do with the oprevious instance and wwant to get for it something which is a part of the first instance - makes no sense.
>I think I understand now - my constructor was doing nothing
the problem is not that your constructior is doing notihing.
You should not have that constructor at all.
You created one such dialog. Your combovboxes of that instance are the ones whith which the usre interacts - you want to deal only with that instance and with thoswe combbioxes. You don't want to create another instance at all.
Don't knwo how to explain it again and again.
the problem is not that your constructior is doing notihing.
You should not have that constructor at all.
You created one such dialog. Your combovboxes of that instance are the ones whith which the usre interacts - you want to deal only with that instance and with thoswe combbioxes. You don't want to create another instance at all.
Don't knwo how to explain it again and again.
You should have a reference to the dialog which you created bevfore in this class where you are now - that very reference to that very instance creted in the first place. And this should be th instance on which you should invoke that method getKeySelections.
You cannot crete ecvery time new instance . You need to pass around this very instance which you creted first time, shich is seen on the screen by the user,
where the user selected these bnoxes. If you crete another instance - it will not be the same thing absolutely.
You cannot crete ecvery time new instance . You need to pass around this very instance which you creted first time, shich is seen on the screen by the user,
where the user selected these bnoxes. If you crete another instance - it will not be the same thing absolutely.
ASKER
I did understand to use the same instance, but when I tried to create the instance in EdiBaseDialog
RequestTransmittalDialog rtd = new RequestTransmittalDialog(r eqTransInf o, ThreedTransIds, proj, modalBlocker, session, appReg);
I was getting a error on modalBlocker.
In the constructor it is Dialog parent
RequestTransmittalDialog rtd = new RequestTransmittalDialog(r
I was getting a error on modalBlocker.
In the constructor it is Dialog parent
ASKER
So when I create the dialog - that is the instance I need to be using and not even have to create a new one.
So you mean you creted one dialog in EdibaseDailog which is modal.
Then it blocked - you will not move forward untli you close this modal dialog.
Only then you can create another dialog in the same code.
In any case you need that all parts of your program always access one and the same instance of your dialog.
Then it blocked - you will not move forward untli you close this modal dialog.
Only then you can create another dialog in the same code.
In any case you need that all parts of your program always access one and the same instance of your dialog.
ASKER
This is where I am creating the dialog
public void startGetReqInfoOperation() {
getReqOp = new EdiGetRequestTransmittalInfoOperation(appReg.getString("edi.message.getReqInfo"), session, this);
getReqOp.addOperationListener(new EdiOperationListener(this) {
protected void endOperationImpl() {
try {
reqTransInfo = getReqOp.getTransmittalInfo();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
showRequestTransmittalDialog();
}
catch (Exception e) {}
}
});
}
finally {
getReqOp.removeOperationListener(this);
getReqOp = null;
}
}
});
session.queueOperation(getReqOp);
} // end startGetReqInfoOperation()
yes - it is always that way - you crete instance of dialog - and all elments bellong to that dioalog and all whut is inside those elements belong to that dialog.
Then it is shown. Then your user interacts it - all that is not in just general class - it is only in that very instance of that classe.
never crete another instance of that class - if you wnat to get that onformation whauch was accumulated in taht first instance of thie class.
You need to find the ways to pass reference to that very instance - only tghis instance has this information which you need.
No matter how many more new kids you create thos new kids will not be born with all the memory in their head as the your fisrt kid hhas - this furst kid knows
a lot of something which a newborn will not know even though he may also havbe two legs and ten fingers etc. - isn't that obvious?
Then it is shown. Then your user interacts it - all that is not in just general class - it is only in that very instance of that classe.
never crete another instance of that class - if you wnat to get that onformation whauch was accumulated in taht first instance of thie class.
You need to find the ways to pass reference to that very instance - only tghis instance has this information which you need.
No matter how many more new kids you create thos new kids will not be born with all the memory in their head as the your fisrt kid hhas - this furst kid knows
a lot of something which a newborn will not know even though he may also havbe two legs and ten fingers etc. - isn't that obvious?
This anotyhe peiece of code syays nothing to me - just undrstand the principlwe once and for all - waht is there not to underastand - you can;t request anything
form the dialog you just created - pass around the reference to that only one which whould be used in all places
form the dialog you just created - pass around the reference to that only one which whould be used in all places
ASKER
I am so confused once again. Â I have no clue why have so much trouble with this instance stuff. Â I downloaded your example code and ran though it pretty good and just when I think I understand it - this happens.
EdiBaseDialog (base dialog)
opens  RequestTransmittalDialog()
Â
so in this code ar is the instance of the dialog RequestTransmittalDialog. Â This would be the instance I need to work with?
Â
EdiBaseDialog (base dialog)
opens  RequestTransmittalDialog()
Â
private void showRequestTransmittalDialog() {
// List workItems = workItemsModel.getAsListOfItems();
RequestTransmittalDialog ar = new RequestTransmittalDialog(reqTransInfo, ThreedTransIds, currentProject, this,
session, appReg);
ar.setModal(true);
ar.setVisible(true);
}
so in this code ar is the instance of the dialog RequestTransmittalDialog. Â This would be the instance I need to work with?
Â
ASKER
could I add something in there like
 RequestTransmittalDialog ar = new RequestTransmittalDialog(r eqTransInf o, ThreedTransIds, currentProject, this,
    session, appReg);
   ar.setModal(true);
   ar.setVisible(true);
   String key = ar.getKeyUserSelect(); Â
}
 RequestTransmittalDialog ar = new RequestTransmittalDialog(r
    session, appReg);
   ar.setModal(true);
   ar.setVisible(true);
   String key = ar.getKeyUserSelect(); Â
}
ASKER
then in the xml code I could just pass in key
sb.append(" Â Â Â Â <KeyUser> + key + </KeyUser>\n");
sb.append(" Â Â Â Â <KeyUser> + key + </KeyUser>\n");
but as soon as you do this:
RequestTransmittalDialog ar = new RequestTransmittalDialog(r eqTransInf o, ThreedTransIds, currentProject, this,
    session, appReg);
you crete only locval instancce ar - which accanot be accesses outside of your method
showRequestTransmittalDial og
So you need to make it instance variable (by declarimng it on top of the class)
and then you should pass this intance variable to your other classes and use it to access specific parts of RequestTransmittalDialog
we went thriough  that situation many times
RequestTransmittalDialog ar = new RequestTransmittalDialog(r
    session, appReg);
you crete only locval instancce ar - which accanot be accesses outside of your method
showRequestTransmittalDial
So you need to make it instance variable (by declarimng it on top of the class)
and then you should pass this intance variable to your other classes and use it to access specific parts of RequestTransmittalDialog
we went thriough  that situation many times
ASKER
Here are the things I have tried before I even posted the question
public class EdiBaseDialog extends AbstractAIFDialog {
RequestTransmittalDialog rtd;
Constructor
My EdiBaseDialog will not open - throws a null pointer
I tried
EdiBaseDialog throws a NPE
The NPE is pointing to this line in the RequestTransmittalDialog  class
keyUserModel = new MyListModel(info.keyUserId s);
So that is when I started trying different things. Â I thought what I did above was the right way
public class EdiBaseDialog extends AbstractAIFDialog {
RequestTransmittalDialog rtd;
Constructor
public EdiBaseDialog(EdiDialogHandler edh, Frame parent, TCSession theSession) {
super(parent, false);
session = theSession;
myModel = SingletonSelectTable.getInstance();
myModel.setEdb(this);
submitButton = myModel.getOKButton();
removeButton = myModel.getButton();
commentButton = myModel.getCommentButton();
this.edh = edh;
this.revdata = revdata;
rtd = new RequestTransmittalDialog(reqTransInfo, ThreedTransIds, currentProject, this, session, appReg);
createDialog();
 } // end ConstructorMy EdiBaseDialog will not open - throws a null pointer
I tried
public class EdiBaseDialog extends AbstractAIFDialog {
RequestTransmittalDialog rtd = new RequestTransmittalDialog(reqTransInfo, ThreedTransIds, currentProject, this, session, appReg);
EdiBaseDialog throws a NPE
The NPE is pointing to this line in the RequestTransmittalDialog  class
keyUserModel = new MyListModel(info.keyUserId
So that is when I started trying different things. Â I thought what I did above was the right way
The java code for class - for any class - is nothing but the template how to create the class.
When you instantiate the class - you make an instance. this isntance is a real thing - it corrsponds to
a big chunk of cells in your computer memory allocated to this instance. And it has a pointer - the address which is associated
with java variable which holds it. Onec you have this variable - you can access any piece of the instance.
When you run another time constructore of the class - you create similar structures chunk of memeory in another place.
So it has some inituial dfata which comes duting initialization, but it does not know anything else which happened with the previous instance.
So if user seklected a string in the combobox of the first instance - it will not at all be reflected in tghis another chunk of
memory cells which you just allocated to a new instance.
So you need to get hold of that old inantsnce tio be ablet to reae that data ahich wqas accuymemulated in that instance
Second variant makes no sense - you try to execute siomething like cretion annew dialog not within constructor or any method - should not do it.
The first variant is more or less how it should be.
Adter that you should provide a method to access to rtd variable (adn in this way to tjhis dialog from another class.
Why and at which place the constructor thorows NPE - is a separate issue - should be debuged and cleared.
You cannot drop it because oif it - should find out the reason and overcome iit.
The first variant is more or less how it should be.
Adter that you should provide a method to access to rtd variable (adn in this way to tjhis dialog from another class.
Why and at which place the constructor thorows NPE - is a separate issue - should be debuged and cleared.
You cannot drop it because oif it - should find out the reason and overcome iit.
ASKER
so if we do like the first example above. Â When EdiBaseDialog opens, it creates a instance of RequestTransmittalDialog, because we put it in the constructor. Â So what happens when I click the button to open the dialog? Â Does it create yet another instance of RequestTransmittalDialog?
ASKER
so in my RequestTransmittalDialog constructor do I need to create a instance of EdiBaseDialog as well?
what is you main class which start everything and what dialogs it opens?
ASKER
EdiBaseDialog - is the base class - it opens RequestTransmittalDialog
so EdiBaseDialog opens first
 and simultaneously you want to open RequestTransmittalDialog?
Or at some later point?
In which dialog you have comboboxwes which you want to read?
In which class you want to read them?
 and simultaneously you want to open RequestTransmittalDialog?
Or at some later point?
In which dialog you have comboboxwes which you want to read?
In which class you want to read them?
ASKER
EdiBaseDialog opens first - yes
at some later point open RequestTransmittalDialog - yes
In which dialog you have comboboxwes which you want to read? - Â RequestTransmittalDialog
In which class you want to read them? - EdiBaseDialog
at some later point open RequestTransmittalDialog - yes
In which dialog you have comboboxwes which you want to read? - Â RequestTransmittalDialog
In which class you want to read them? - EdiBaseDialog
Something like that:
public class EdiBaseDialog implements ActinListener {
RequestTransmittalDialog rtd;
public EdiBaseDialog(...) {
// do something - you may or may not create RequestTransmittalDialog here
// you may crete it also in some other method, say when user preses the button - in action perfprmed
JButton btn = new JButton(..)
btn.addActionListener(this );
}
...
public void actionPerformed(ActionEven t ae) {
if(ae.getSource().equals(b tn) {
// do something
rtd = new RequestTransmittalDialog (...);
rtd.setSize();
rtd.setVisible(true);
}
}
...
// in some other method of this class
// either in actinPerfomed() or asomewhere else:
public void method () {  // you need to be absolutely sure that this method is called only after the  RequestTransmittalDialog() is created
// and not only created, but actually shown to the suser and user should have tuime to select something
// otherwise it does not make snesen
String s1 = rtd.getUseKeySelection();
}
}
in
class RequestTransmittalDialog {
JComboBox keyUserSelection;
public RequestTransmissionDialog( ) {
// do somthing
// create and place the boxes
keyUserSelection = new JComboBox(..);
}
public String getUserSelection() {
return keyUserSelection.getSelect edItem();
}
}
public class EdiBaseDialog implements ActinListener {
RequestTransmittalDialog rtd;
public EdiBaseDialog(...) {
// do something - you may or may not create RequestTransmittalDialog here
// you may crete it also in some other method, say when user preses the button - in action perfprmed
JButton btn = new JButton(..)
btn.addActionListener(this
}
...
public void actionPerformed(ActionEven
if(ae.getSource().equals(b
// do something
rtd = new RequestTransmittalDialog (...);
rtd.setSize();
rtd.setVisible(true);
}
}
...
// in some other method of this class
// either in actinPerfomed() or asomewhere else:
public void method () {  // you need to be absolutely sure that this method is called only after the  RequestTransmittalDialog()
// and not only created, but actually shown to the suser and user should have tuime to select something
// otherwise it does not make snesen
String s1 = rtd.getUseKeySelection();
}
}
in
class RequestTransmittalDialog {
JComboBox keyUserSelection;
public RequestTransmissionDialog(
// do somthing
// create and place the boxes
keyUserSelection = new JComboBox(..);
}
public String getUserSelection() {
return keyUserSelection.getSelect
}
}
public void method () {  // you need to be absolutely sure that this method is called only after the  RequestTransmittalDialog()
// and not only created, but actually shown to the suser and user should have tuime to select something
// otherwise it does not make snesen  - therefore this method should not be callsed immediately just after you create
//rtd
It may be clled friom the same actionPerforemed() method but in another conditiobnla branch - niot immedaitely after
creation iof rtd - it simply would not make sense
OK. I'm gone for the next 1.5 hours
ASKER
I will try and get this working first thing in the morning.