• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 458
  • Last Modified:

Creating a new ArrayList

I have one class that is creating a ArrayList of user selections.  This is class is called from a right mouse click.  I have another class that is called from a menu click.  This class creates a dialog and then gets the ArrayList from the other class and creates a Table.

The two classes are seperate and the user can select the menu option before the right mouse click. So when the table is trying to be built it is throwing a NULL POINTER, because the ArrayList does not exist.  

So what I am trying to do is when the Menu option is clicked it will check and see if the ArrayList exist, if the ArrayList does not exist it will go ahead and create a new ArrayList with nothing in it.

I am not sure where to put the check.  I have tried a couple of differnt places with no luck.

This is the class that gets called first - this one calls the main dialog class

 
public class EdiDialogHandler extends AbstractHandler {
	
	/* The constructor */
	
	public EdiDialogHandler() {
		
   }
       
   @Override
   public Object execute(final ExecutionEvent event) throws ExecutionException {
	   //ediBaseDialog  = new ediBaseDialog();ediSelection.getMap();
	   TCSession theSession = (TCSession)AIFDesktop.getActiveDesktop().getCurrentApplication().getSession();   
	   showediDialog(theSession);
	   return null;
   }
   private void showediDialog(TCSession theSession) {
		 EdiBaseDialog ar = new EdiBaseDialog(null, theSession);
		 ar.setModal(false);
	  	 ar.setVisible(true);  
	    }    

}

Open in new window


This is the main dialog class and the method  selectedTable is where I create the table

 
public class EdiBaseDialog extends AbstractAIFDialog{
   private static final long serialVersionUID = 1L;
   private EdiProject currentProject     = null;
   private JLabel curProjectLabel    = null;
   private JLabel cur3DTransLabel    = null;
   private JLabel cur2DTransLabel    = null;
   private JLabel curEmailLabel    = null;
   private JLabel tableLabel    = null;
   
   private JPanel centerPanel = null; 
   private JTable selectTable = null;
   private TCSession session = null; 
   private Registry appReg = null;
  
   
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                              Constructor                             //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   public EdiBaseDialog(Frame parent, TCSession theSession){
	   super(parent, false);
	   session = theSession;
	   SelectedTModel es = new SelectedTModel();
	   createDialog();  
	  
   } //end Constructor
     
   
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                            createDialog()                            //
   //                                                                      //
   ////////////////////////////////////////////////////////////////////////// 
   public void createDialog() {
	  
	  appReg = Registry.getRegistry(this);
	  setTitle(appReg.getString("edi.TITLE"));
	   
	  Component selectionsPanel = selectedTable();
	  Component buttonPanel = OKCancelButtons();
	  Component currentPanel = currentItems();
	  centerPanel = new JPanel();
      centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
      centerPanel.setPreferredSize(new Dimension(750, 350));
      
      centerPanel.add(Box.createRigidArea(new Dimension(5, 0)));
      centerPanel.add(currentPanel);
      centerPanel.add(selectionsPanel);
      centerPanel.add(Box.createHorizontalGlue());
      centerPanel.add(Box.createRigidArea(new Dimension(0, 2)));
      centerPanel.add(buttonPanel);
      
      getContentPane().add(centerPanel);
      
      addComponentListener(new ComponentAdapter() {
        public void componentResized(ComponentEvent event) {
           Component c = event.getComponent();
           c.setSize(Math.max((int)centerPanel.getPreferredSize().getWidth()/2, c.getWidth()),
                     Math.max((int)centerPanel.getPreferredSize().getHeight()/2, c.getHeight()));
        }
      });
        	  	
      this.pack();
      setLocation(getParent().getLocation(null));        
         
      //Display the window.
      centerPanel.setVisible(true);
      
      
   
   
   
   }// end createDialog()
   
   private void showProjectSelectDialog() {
      EdiSelectProjectDialog ar = new EdiSelectProjectDialog(this, session, appReg);
	  ar.setModal(true);
	  ar.setVisible(true);  
   } 
   
   private void showProjectTranslatorsDialog() {
      EdiProjectTranslatorsDialog ar = new EdiProjectTranslatorsDialog(currentProject, this, appReg);
	  ar.setModal(true);
	  ar.setVisible(true);  
   } 

   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                        OKCancelButtons()                             //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   private JPanel OKCancelButtons() {
      JButton okButton = new JButton("Submit");
      okButton.setEnabled(true);
      okButton.addActionListener(new ActionListener() {
   
         public void actionPerformed(ActionEvent e) {
        	 EdiSelection.clearList();
        	 dispose();
         }
      });

      JButton cancelButton = new JButton("Cancel");
      cancelButton.setEnabled(true);
      cancelButton.addActionListener(new ActionListener() {
      
	     public void actionPerformed(ActionEvent e) {
            dispose();
         }
      });

      JPanel p = new JPanel();
      //p.setBorder(BorderFactory.createLineBorder(Color.red));
      p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
      p.add(Box.createHorizontalGlue());
      p.add(okButton);
      p.add(cancelButton);

   return p;
   }// end OKCancelButtons()

   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                           set_gbc()                                  //
   //                       GridBagConstraints                             //
   //                                                                      // 
   //////////////////////////////////////////////////////////////////////////
   GridBagConstraints gbc = new GridBagConstraints();
   protected boolean alreadyEnabled;

   private void set_gbc(int row, int column, int width, int height, int fill) {
      gbc.gridy = row;
      gbc.gridx = column;
      gbc.gridwidth = width;
      gbc.gridheight = height;
      gbc.fill = fill;   // GridBagConstraints.NONE .HORIZONTAL .VERTICAL .BOTH
   }

   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                             selectedTable()                          //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   private JPanel selectedTable(){
	  
    tableLabel = new JLabel();
    
	JPanel p = new JPanel();
	//p.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
    //p.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
	GridBagLayout gridbag = new GridBagLayout();
    p.setLayout(gridbag);
    
    TableModel myModel = new SelectedTModel();
	// Create a new table instance
	selectTable = new JTable(myModel);
	selectTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
	selectTable.setCellSelectionEnabled(false);
	selectTable.setRowSelectionAllowed(true);
	selectTable.setColumnSelectionAllowed(false);
	//selectTable.setMinimumSize(table.getPreferredSize());

	// Add the table to a scrolling pane
	JScrollPane ScrollPane = new JScrollPane(selectTable);
		   
	gbc.insets = new Insets(5,10,10,5);      
    set_gbc(0, 0, 1, 1,GridBagConstraints.BOTH );
    tableLabel = new JLabel(appReg.getString("edi.tableLabel"));
    gridbag.setConstraints(tableLabel, gbc);
    p.add(tableLabel);
	
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.gridheight = 1;
    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.BOTH; 
    //set_gbc(0, 1, 1, 1,GridBagConstraints.BOTH );
    //gridbag.setConstraints(ScrollPane, gbc);
    
    p.add(ScrollPane,gbc);
    
    return p;
   }// end selectedTable() 


   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                        currentItems()                                //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   private JPanel currentItems(){
	   
      
	  //JLabel eLabel = new JLabel("Current Project");
	  curProjectLabel = new JLabel();
	  cur3DTransLabel = new JLabel();
	  cur2DTransLabel = new JLabel();
	  curEmailLabel = new JLabel();
	   
	  final JTextField curProject = new JTextField(20);
	  curProject.setEnabled(false);
	  
	  
	  final JTextField cur3dTrans = new JTextField(20);
	  cur3dTrans.setEnabled(false);
	  final JTextField cur2dTrans = new JTextField(20);
	  cur2dTrans.setEnabled(false);
	  final JTextField curEmails = new JTextField(20);
	  curEmails.setEnabled(false);
	  
	  final JButton projectButton = new JButton("Change");
      //projectButton.setBackground(Color.cyan);
      //projectButton.setForeground(Color.cyan); 
      projectButton.setPreferredSize(new Dimension(100, 20));
      projectButton.setEnabled(true);
      projectButton.addActionListener(
      new ActionListener() {
         public void actionPerformed( ActionEvent event )
         {
        	 showProjectSelectDialog(); 
        	 //dispose();   
         }           
      });
      final JButton threeDButton = new JButton("Change");
      //projectButton.setBackground(Color.red);
      //projectButton.setForeground(Color.cyan); 
      threeDButton.setPreferredSize(new Dimension(100, 20));
      if (currentProject != null) {
    	  threeDButton.setEnabled(false);
       }
       else {
    	   threeDButton.setEnabled(true); 
       }
      threeDButton.addActionListener(
      new ActionListener() {
         public void actionPerformed( ActionEvent event )
         {
        	 showProjectTranslatorsDialog();
        	 //dispose();   
         }           
      });
      final JButton twoDButton = new JButton("Change");
      //projectButton.setBackground(Color.red);
      //projectButton.setForeground(Color.red); 
      twoDButton.setPreferredSize(new Dimension(100, 20));
      if (currentProject != null) {
    	  twoDButton.setEnabled(true);
       }
       else {
    	   twoDButton.setEnabled(false); 
       }
      twoDButton.addActionListener(
      new ActionListener() {
         public void actionPerformed( ActionEvent event )
         {
         	dispose();   
         }           
      });
      final JButton emailButton = new JButton("Change");
      //projectButton.setBackground(Color.red);
      //projectButton.setForeground(Color.red); 
      emailButton.setPreferredSize(new Dimension(100, 20));
      if (currentProject != null) {
    	  emailButton.setEnabled(true);
       }
       else {
    	   emailButton.setEnabled(false); 
       }
      emailButton.addActionListener(
      new ActionListener() {
         public void actionPerformed( ActionEvent event )
        {
        	dispose();   
        }           
      });
		
	 JPanel p = new JPanel();
     //p.setBorder(BorderFactory.createLineBorder(Color.green));
     GridBagLayout gridbag = new GridBagLayout();
     p.setLayout(gridbag);
     
     //Labels
     gbc.insets = new Insets(5,10,10,5);      
     set_gbc(0, 0, 1, 1,GridBagConstraints.HORIZONTAL );
     curProjectLabel = new JLabel(appReg.getString("edi.currentProject"));
     gridbag.setConstraints(curProjectLabel, gbc);
     p.add(curProjectLabel);
    
     set_gbc(1, 0, 1, 1,GridBagConstraints.HORIZONTAL );
     cur3DTransLabel = new JLabel(appReg.getString("edi.current3dTrans"));
     gridbag.setConstraints(cur3DTransLabel, gbc);
     p.add(cur3DTransLabel);
    
     set_gbc(2, 0, 1, 1,GridBagConstraints.HORIZONTAL );
     cur2DTransLabel = new JLabel(appReg.getString("edi.current2dTrans"));
     gridbag.setConstraints(cur2DTransLabel, gbc);
     p.add(cur2DTransLabel);
     
     set_gbc(3, 0, 1, 1,GridBagConstraints.HORIZONTAL );
     curEmailLabel = new JLabel(appReg.getString("edi.currentEmail"));
     gridbag.setConstraints(curEmailLabel, gbc);
     p.add(curEmailLabel);
     
     //Text Fields    
     set_gbc(0, 1, 1, 1,GridBagConstraints.HORIZONTAL);
     gridbag.setConstraints(curProject, gbc);
     p.add(curProject);
    
     set_gbc(1, 1, 1, 1,GridBagConstraints.HORIZONTAL);
     gridbag.setConstraints(cur3dTrans, gbc);
     p.add(cur3dTrans);
    
     set_gbc(2, 1, 1, 1,GridBagConstraints.HORIZONTAL);
     gridbag.setConstraints(cur2dTrans, gbc);
     p.add(cur2dTrans);
    
     set_gbc(3, 1, 1, 1,GridBagConstraints.HORIZONTAL);
     gridbag.setConstraints(curEmails, gbc);
     p.add(curEmails);
     
     //Buttons    
     set_gbc(0, 2, 1, 1, GridBagConstraints.BOTH);
     gridbag.setConstraints(projectButton, gbc);
     p.add(projectButton);
    
     set_gbc(1, 2, 1, 1, GridBagConstraints.BOTH);
     gridbag.setConstraints(threeDButton, gbc);
     p.add(threeDButton);
    
     set_gbc(2, 2, 1, 1, GridBagConstraints.BOTH);
     gridbag.setConstraints(twoDButton, gbc);
     p.add(twoDButton);
    
     set_gbc(3, 2, 1, 1, GridBagConstraints.BOTH);
     gridbag.setConstraints(emailButton, gbc);
     p.add(emailButton);
     return p;
   }// currentItems()

Open in new window


THis si the class that takes in the ArrayList and creates the table that displays

 
public class SelectedTModel extends AbstractTableModel {
   
   private static final long serialVersionUID = 1L;
   private ArrayList<RevDataset> aList;
   
   static final int ITEMID_COL   = 0;
   static final int REVID_COL    = 1;
   static final int PRL_COL      = 2;
   static final int DATASETNAME_COL  = 3;
   static final int DATASET_COL  = 4;
   
   static final int MAX_COLUMNS  = 5;
      
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                              Constructor                             //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   public SelectedTModel() {
      super();
      this.aList = EdiSelection.rds;	  
                
   } // end constructor
   
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                             getColumnCount()                         //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   public int getColumnCount() {
	   
      return MAX_COLUMNS;
   } // end getColumnCount()
   
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                             getRowCount()                            //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////   
   public int getRowCount() {
      return aList.size();
	  
   } // end getRowCount()
   
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                             getValueAt()                             //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////  
   public Object getValueAt(int row, int column){
      Object o = null;
           
	  try {	   
	     switch (column) {
	        case ITEMID_COL: { o = aList.get(row).rev.getItem().getStringProperty("item_id"); break; }
	        case REVID_COL: { o = aList.get(row).rev.getStringProperty("item_revision_id"); break; }
	        case PRL_COL: { o = aList.get(row).rev.getRelatedComponent("IMAN_master_form_rev").getStringProperty("object_name"); break; }
	        case DATASETNAME_COL: { o = aList.get(row).componentdataset.getStringProperty("object_string"); break; }
	        case DATASET_COL: { o = aList.get(row).componentdataset.getStringProperty("object_type"); break; }
	     }
	  }
	  catch (Exception e) {
	     e.printStackTrace();
	 
      } 
      return o;
   }
   
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                             getColumnName()                          //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   public String getColumnName(int column) {
      String s = null;
      
      switch (column) {
      case ITEMID_COL:   { s = "ItemId"; break; }
      case REVID_COL:    { s = "RevId"; break; }
      case PRL_COL:      { s = "PRL"; break; }
      case DATASETNAME_COL:  { s = "Dataset Name"; break; }
      case DATASET_COL:  { s = "Dataset Type"; break; }
      }
   return s;
   } // end getColumnName()
 
}//end SelectedTModel

Open in new window



I thought the check would be something like

if(aList == null) {
           aList  = new ArrayList<RevDataset>();
}

No clue where to check to make sure that the ArrayList is valid and create a new one if it is not valid?
0
jkteater
Asked:
jkteater
  • 8
  • 5
1 Solution
 
for_yanCommented:
I think you have not very good logic.

You believe that your clients will start slecting some data.

So in the very beginning before this starts happnening you create your arraylisty - so that you'll be sure it always exists - just at the start

then when user slescte you populate it

when you then finsdihed and pass this list to the next module - over there you should not need to chek if the list
exists - it should exist always - you just need to chek if it has at leas one eleent and if not -
then skip yout table or print some default wempty table or somthing kilike that
0
 
for_yanCommented:
This is more or less the same as previous-  a little bit elaborated:

Just identify the very begiining point  (mayeb asy in the construyctor of your class - or at the start of the mthod
which is calleed to initiate this collection of slecetions from the user.
At that moment before everything create your aList

  aList  = new ArrayList<RevDataset>();


then in the process of interaction with the user just populate it.
then pass it to the next step
and there you don't need to check if it is null
just check if(aList.size() > 0)

Of course it is impossible to give you ultimate advice without knowing the whole flow
but based on what you describe that seems resonable way of doing things

0
 
jkteaterAuthor Commented:
I don't understand.

If I create a ArrayList at the start of my class 2.  How will the program know to check for the ArrayList created in class 1?

You have to remember that Class 1 and Class 2 are executed separately and really are two seperate programs.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
for_yanCommented:
If you are passing this arraylist between them, they are absolutely the same java application

It does not matter where you create ArrayList - I think you have a class which is responsible for collection of inform,ation from the user.
In that class you create your ArrayList. If the whiole process happens in one method of this class then create ArrayList at the beginnig of the method
If this process happens across the class in many methods - then make ArrayList instance variable and create it every time just before the newe use
is supposed to start sleceting data.

Then you now somehow pass this ArrayList to the next module - so pass it - it will never be null, because it was created before any user activity
but if user did not select anything it will conatin 0 elements.
that is waht you want to check befiore you start processing this array list
0
 
for_yanCommented:
If you can strip away your code of external depndencies (like AIFDailog, etc) and post it so that I can compile and execute it - I would have shown you
it in the code.
Otherwise such lengthy piece of code which I cannot compile is of little use, at least to me.
I'm not a compiler I can't digest all of it in any reasonable time.

So I'm trying to communicate to you the general logic  which helped me many times and  I don't see that there is any reason why this logic would not work for you.
0
 
jkteaterAuthor Commented:
I am sorry that this is taking me so long to get.  You are defining it well, I am just slow today.
If the user right mouse clicks and creates the ArrayList rds.  
Then the user clicks the menu command and that class executes and we create a new ArrayList

so now I have one ArrayList rds with user selections and I have one ArrayList ?? just created.
So now how I do get the values from rds to the new ArrayList.  Do I check and see if rds exist and if it does I assign the rds to the new ArrayList created?  and if it does not exist I pass in the new ArrayList to the jtable?
0
 
for_yanCommented:

I don't think you need to have two ArrayLists

lets try this way:


>This is class is called from a right mouse click
lets call this ClassA

>This class creates a dialog and then gets the ArrayList from the other class and creates a Table.
lets call this ClassB


In the headr of ClassA
you declare
ArrayList<..> aList;

in constructor opf ClassA
you create


 aList = new ArrayList<...>();

So now long before any user you have non-null instance of the ArrayList aList - it is like
a reservoir - it is now empty, but it exists - so it is not null

when new user goes to ClassA first time to create slections
you write

aList.clear(); - you do it first time - so that you don;'t have remnants of other users slections there

As user selects stuff you keep adding data to aList

aList.add(new...);


then in ClassB when you assume that user finished his/her activity you get this ArrayList

you get some instance of ClassA, say called classA and you have some method of ClasssA
say classA.getArrayList()
or something

so in ClassB somewher you say

ArrayList<... >gotList = classA.getArryList();

At this moment what user accumulated in aList
you now have in ClassB and in this example it is called

gotList (or what ever you call it)

You are sure that gotList is not null,
because you created it long befiore  before any user activity
independnt of whehete user wanted to slecte anything

However user could either have put soemthing there or not,
so it can have some elements or it can have zero elements

So you just check:

if(gotList.szie() > 0) //go ahead and make a table
else // go ahead and make a message that user did not input anything

Please, try to read the above and explain to me in these terminology what I am missing and
what cannot be done in this way.

Don't think about your classes as separate worlds - this is one java program - if you can pass parameters between these classes - it is
for all purposes one application and your only goal that these classes interact
consistently with each other. if necessary you can add methiods to these classes to make them
interact more correctly and so on. Don't worry that they are different classes - it is one program.








0
 
jkteaterAuthor Commented:
Very well explained.  

But what happens when the user does not click class a first.  The arrayList never gets created.  So I am trying to create a table with no array to build it.
0
 
for_yanCommented:
In these scheme ArrayList creation is associated with creation of classA - so if classA was never created
then whay would classB want to get access of any arraylist? The there would not be even any instance of classA
in classB. Well you certainly can check for that in classB,

How you are getting the connection to classA from classB ?

How do you getting this list?

If it is in the way I showed above then even before you call
classA .getArtrayList()
you need to check that
cllassA is not null


0
 
jkteaterAuthor Commented:
It is true that class b can be executed without class a ever being executed.  There are other values on the class B dialog other than the table.

Here are the values that are on the dialog from class b

project [  ]
3d trans [ ]
2d trans [ ]
email [ ]
jtable [                                   ]

jtable is populate from the ArrayList we have been talking about.  The user should be able to still open the dialog and change the top 4 values without having to worry with the table.  So there are some times the user will execute class B without getting selections from class A.  So in class be I need to see if the ArrayList is created, if it is not created I need to create a dummy ArrayList so that the jtable will not spit out NULL POINTERS.

THis is how I am getting the ArrayList from Class A

 //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                              Constructor                             //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   public SelectedTModel() {
      super();
      this.aList = EdiSelection.rds;       
               
   } // end constructor

This is the constructor for the table creation class.

TableModel myModel = new SelectedTModel();
      // Create a new table instance
      selectTable = new JTable(myModel);

This is how I am creating my TableModel

0
 
for_yanCommented:

for simplicity make it this way:
  public SelectedTModel() {
      super();
      this.aList = EdiSelection.rds;   
 if(aList == null) aList = new ArrayList<...>();     
                
   } // end constructor

Open in new window


then you'll never have to deal with null aList
0
 
jkteaterAuthor Commented:
That was it!!!  Thanks so much for all your help.
0
 
for_yanCommented:
You are always welcome
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 8
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now