Solved

Function to return a model

Posted on 2011-03-22
16
270 Views
Last Modified: 2012-05-11
I have asked a very similar question and received a very good answer.  But the lead programmer on the project prefers it done a different way.

I have a class file VendorEmail that creates a abstractlistmodel - the user is allowed to add and remove email address from the list.  Once that are finished, there is an OK button for them to click.

I need to write a function in VendorEmail that will return the model with the values.  So when the OK button is clicked the function is called and I can pass that model to the parent class dialog.  I do understand there are other ways of doing this, but the prefer method is the function explained above.

thanks to everyone that can help on this
0
Comment
Question by:jkteater
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
  • 2
  • +1
16 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 35193691
I thought i'd gone through this..?
public SortableListModel getModel() {
    return foo; // ( Can't remember what your model variable is called )
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35194149
I think that variable was called "model"
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35194174
OK, so it would be

return model;
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 35196309
I think its jsut a list value ... u can retun as list that engough !
0
 

Author Comment

by:jkteater
ID: 35198199
Do I have to pass the model in to the function?  what I have below is not working.

error on the return line  = can not resolve model
final SortingListModel model = new SortingListModel();

public SortingListModel getModel() {
        return model; 
    }

Open in new window

0
 
LVL 20

Expert Comment

by:Sathish David Kumar N
ID: 35198236

public SortingListModel getModel() {  
   final SortingListModel model = new SortingListModel();  

        return model;  
    }
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35198249

>>error on the return line  = can not resolve model

There's nothing wrong with the code you posted. Please copy and paste the error message
0
 

Author Comment

by:jkteater
ID: 35198293
return model;
             ^^^^^
model cannot be resolved

That is what is in the log file
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35198364
Then you  didn't declare and initialise the model as you showed in your code
0
 

Author Comment

by:jkteater
ID: 35198387
I will paste what I have.

First code is where I am sitting it up
second code is where I am using the model to sort and that is followed by the new function
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        SortingListModel                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////  
    
    public class SortingListModel extends AbstractListModel
    {
    	TreeSet model;
        
    	private Comparator USEFUL_COMPARATOR = new Comparator()
            {
                public int compare( Object o1, Object o2 )
                {
                    String str1 = o1.toString();
                    String str2 = o2.toString();
                    Collator collator = Collator.getInstance();
                    int result = collator.compare( str1, str2 );
                    return result;
                }
            };

    public SortingListModel()
    {
        model = new TreeSet( USEFUL_COMPARATOR );
    }

    // ListModel methods
    public int getSize()
    {
        // Return the model size
        return model.size();
    }

    public Object getElementAt( int index )
    {
        // Return the appropriate element
        return model.toArray()[index];
    }

    // Other methods
    public void addElement( Object element )
    {
        
        if( model.add( element ))
        {
            fireContentsChanged( this, 0, getSize() );
        }
    }

    public void addAll( Object elements[] )
    {
        Collection c = Arrays.asList(elements);
        model.addAll(c);
        fireContentsChanged( this, 0, getSize() );
    }

    public void clear()
    {
        model.clear();
        fireContentsChanged( this, 0, getSize() );
    }

    public boolean contains( Object element )
    {
        return model.contains( element );
    }

    public Object firstElement()
    {
        // Return the appropriate element
        return model.first();
    }

    public Iterator iterator()
    {
        return model.iterator();
    }

    public Object lastElement()
    {
        // Return the appropriate element
        return model.last();
    }

    public boolean removeElement( Object element )
    {
        boolean removed = model.remove( element );
        if( removed )
        {
            fireContentsChanged( this, 0, getSize() );
        }
        return removed;
    }

 }
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        getModel()                                    //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    public SortingListModel getModel() {
        return model; 
    }

Open in new window

private JPanel EmailList(){
    	 
    	final JTextField addEmail = new JTextField(20);
    	ArrayList arrayList = new ArrayList();
    	JLabel eLabel = new JLabel("Additional Emails");
    	JLabel ListLabel = new JLabel("Existing Vendor Emails");
    	
    	String[] emails = project.getEmailAddresses();	    	
    	//listModel = new DefaultListModel();
    	//SortingListModel model = new SortingListModel();
        //    	 fill model
    	final SortingListModel model = new SortingListModel();
    	
    	
    	for (int i = 0; i < emails.length; ++i) {
         	//listModel.addElement( emails[i]);       	
              model.addElement(emails[i]);      
        }    	    	
               
        final JList AltList = new JList(model);
    	AltList.setBorder(BorderFactory.createLoweredBevelBorder());
    	AltList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    	AltList.setLayoutOrientation(JList.VERTICAL);
    	AltList.setVisibleRowCount(4);
    	JScrollPane acrossScrollBar= new JScrollPane(AltList);

Open in new window

0
 

Author Comment

by:jkteater
ID: 35198391
Reverse 1 and 2
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35199669
getModel should be in VendorEmail, not SortingListModel
0
 

Author Comment

by:jkteater
ID: 35200816
I am sorry CEHJ - Not sure why I am having much problems with something so simple.  I am going to paste my entire code and please so me where to put the new function
public class VendorEmailDialog extends JDialog {
	private TCSession session = null;
	private Registry appReg = null;
	private EdiGetRequestTransmittalInfoOperation getReqOp = null;
	private EdiGetRequestTransmittalInfoOperation.TransmittalInfo reqTransInfo = null;
	private EdiProject  project = null;
	private DefaultListModel listModel;
    JLabel label;
    private JPanel centerPanel = null;
    JPanel cards;
    protected JTextField textField;
 
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                              Constructor                             //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
   
    public VendorEmailDialog(TransmittalInfo reqTransInfo,EdiProject currentProject, Dialog parent, TCSession theSession, Registry theRegistry){
    //public VendorEmailDialog(Dialog parent){       
    super(parent,"Vendor Email Dialog", true);
	       session = theSession;
	       appReg = theRegistry;
	       project = currentProject;
	       createDialog();
	} // end constructor
    
     
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             createDialog()                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

    private void createDialog() {
    	
    	Component listPanel = EmailList();
    	Component buttonPanel = OKCancelButtons();
    	    	
    	centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
        centerPanel.setPreferredSize(new Dimension(600, 200));

        centerPanel.add(Box.createRigidArea(new Dimension(5, 0)));
        centerPanel.add(listPanel);
        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()
   
      
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             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
    }
   
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             Validating Email                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    public boolean isValidEmailAddress(String emailAddress){  
    String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";  
    CharSequence inputStr = emailAddress;  
    Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);  
    Matcher matcher = pattern.matcher(inputStr);  
    return matcher.matches();  
 
    }      

    
    
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             EmailList()                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    private JPanel EmailList(){
    	 
    	final JTextField addEmail = new JTextField(20);
    	ArrayList arrayList = new ArrayList();
    	JLabel eLabel = new JLabel("Additional Emails");
    	JLabel ListLabel = new JLabel("Existing Vendor Emails");
    	
    	String[] emails = project.getEmailAddresses();	    	
    	//listModel = new DefaultListModel();
    	//SortingListModel model = new SortingListModel();
        //    	 fill model
    	final SortingListModel model = new SortingListModel();
    	
    	
    	for (int i = 0; i < emails.length; ++i) {
         	//listModel.addElement( emails[i]);       	
              model.addElement(emails[i]);      
        }    	    	
               
        final JList AltList = new JList(model);
    	AltList.setBorder(BorderFactory.createLoweredBevelBorder());
    	AltList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    	AltList.setLayoutOrientation(JList.VERTICAL);
    	AltList.setVisibleRowCount(4);
    	JScrollPane acrossScrollBar= new JScrollPane(AltList); 
     	
    	// addButton Code //
    	
    	final JButton addButton = new JButton("Add >>");
    	//addButton.setBackground(Color.green);
    	//addButton.setForeground(Color.green); 
    	addButton.setEnabled(true);
        addButton.addActionListener(new ActionListener() {
        
        public void actionPerformed(ActionEvent e) {
           String name = addEmail.getText();
           
             
           if(isValidEmailAddress(name)) {  
        		  
        		   //User didn't type in a unique name...
        	   Component object = null;
        	   if (name.equals("") || alreadyInList(name)) {
        		   Toolkit.getDefaultToolkit().beep();
        		   JOptionPane.showMessageDialog(object,name + "Email Address Already In List");
        		   addEmail.requestFocusInWindow();
        		   addEmail.selectAll();
        		   return;
        	   }

        	   int index = AltList.getSelectedIndex(); //get selected index
        	   if (index == -1) { //no selection, so insert at beginning
        		   index = 0;
        	   } 
        	   else {           //add after the selected item
                  index++;
        	   }

        	   //listModel.insertElementAt(addEmail.getText(), index);
        	   model.addElement(addEmail.getText());
        	   //If we just wanted to add to the end, we'd do this:
        	   //listModel.addElement(employeeName.getText());
       		   //Reset the text field.
       		   addEmail.requestFocusInWindow();
       		   addEmail.setText("");
       		   //Select the new item and make it visible.
       		   AltList.setSelectedIndex(index);
       		   AltList.ensureIndexIsVisible(index);
       	   }
       	   else{  
       		   Component object = null;
       		   JOptionPane.showMessageDialog(object,name + "Is not valid Email Address");
       		   //addEmail.requestFocusInWindow();
       		   //addEmail.setText("");
       		  
       	   }  
        }
        

           //This method tests for string equality. You could certainly
           //get more sophisticated about the algorithm.  For example,
           //you might want to ignore white space and capitalization.
           protected boolean alreadyInList(String name) {
               return model.contains(name);
           }

           //Required by DocumentListener.
           public void insertUpdate(DocumentEvent e) {
               enableButton();
           }

           //Required by DocumentListener.
           public void removeUpdate(DocumentEvent e) {
               handleEmptyTextField(e);
           }

           //Required by DocumentListener.
           public void changedUpdate(DocumentEvent e) {
               if (!handleEmptyTextField(e)) {
                   enableButton();
               }
           }

           private void enableButton() {
               if (!alreadyEnabled) {
                   addButton.setEnabled(true);
               }
           }

           private boolean handleEmptyTextField(DocumentEvent e) {
               if (e.getDocument().getLength() <= 0) {
                   addButton.setEnabled(false);
                   alreadyEnabled = false;
                   return true;
               }
               return false;
           } 
                  
           });
        
        // removeButton //
        
        final JButton removeButton = new JButton("Remove <<");
        //removeButton.setBackground(Color.red);
        //removeButton.setForeground(Color.red); 
        removeButton.setPreferredSize(new Dimension(100, 40));
        removeButton.setEnabled(true);
        removeButton.addActionListener(
        new ActionListener() {
           public void actionPerformed( ActionEvent event )
          {
        	   int index = AltList.getSelectedIndex();
               //listModel.remove(index);
        	   Object str = model.getElementAt(index);
        	    
               model.removeElement(str);
               int size = model.getSize();

               if (size == 0) { //Nobody's left, disable firing.
                   removeButton.setEnabled(false);

               } else { //Select an index.
                   if (index == model.getSize()) {
                       //removed item in last position
                       index--;
                   }

                   AltList.setSelectedIndex(index);
                   AltList.ensureIndexIsVisible(index);
               }   
          }           
         });
        
        
        
        JPanel p = new JPanel();
        //p.setBorder(BorderFactory.createLineBorder(Color.blue));
        GridBagLayout gridbag = new GridBagLayout();
        p.setLayout(gridbag);
        
        gbc.insets = new Insets(5,10,10,5);      
        set_gbc(0, 0, 1, 1,GridBagConstraints.BOTH );
        gridbag.setConstraints(eLabel, gbc);
        p.add(eLabel);
        
        set_gbc(0, 2, 1, 1,GridBagConstraints.BOTH );
        gridbag.setConstraints(ListLabel, gbc);
        p.add(ListLabel);
               
        set_gbc(1, 0, 1, 1,GridBagConstraints.HORIZONTAL);
        gridbag.setConstraints(addEmail, gbc);
        p.add(addEmail);
                
        set_gbc(1, 2, 1, 3, GridBagConstraints.HORIZONTAL);
        gbc.anchor = GridBagConstraints.PAGE_END; //bottom of space
        gbc.weightx = 3.0;
        gridbag.setConstraints(acrossScrollBar, gbc);
        p.add(acrossScrollBar);
        
        
        set_gbc(1, 1, 1, 1,GridBagConstraints.BOTH);
        gridbag.setConstraints(addButton, gbc);
        p.add(addButton);
        
        set_gbc(2, 1, 1, 1, GridBagConstraints.BOTH);
        gridbag.setConstraints(removeButton, gbc);
        p.add(removeButton);
                                    
        return p;
 }

//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        SortingListModel                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////  
    
    public class SortingListModel extends AbstractListModel
    {
    	TreeSet model;
        
    	private Comparator USEFUL_COMPARATOR = new Comparator()
            {
                public int compare( Object o1, Object o2 )
                {
                    String str1 = o1.toString();
                    String str2 = o2.toString();
                    Collator collator = Collator.getInstance();
                    int result = collator.compare( str1, str2 );
                    return result;
                }
            };

    public SortingListModel()
    {
        model = new TreeSet( USEFUL_COMPARATOR );
    }

    // ListModel methods
    public int getSize()
    {
        // Return the model size
        return model.size();
    }

    public Object getElementAt( int index )
    {
        // Return the appropriate element
        return model.toArray()[index];
    }

    // Other methods
    public void addElement( Object element )
    {
        
        if( model.add( element ))
        {
            fireContentsChanged( this, 0, getSize() );
        }
    }

    public void addAll( Object elements[] )
    {
        Collection c = Arrays.asList(elements);
        model.addAll(c);
        fireContentsChanged( this, 0, getSize() );
    }

    public void clear()
    {
        model.clear();
        fireContentsChanged( this, 0, getSize() );
    }

    public boolean contains( Object element )
    {
        return model.contains( element );
    }

    public Object firstElement()
    {
        // Return the appropriate element
        return model.first();
    }

    public Iterator iterator()
    {
        return model.iterator();
    }

    public Object lastElement()
    {
        // Return the appropriate element
        return model.last();
    }

    public boolean removeElement( Object element )
    {
        boolean removed = model.remove( element );
        if( removed )
        {
            fireContentsChanged( this, 0, getSize() );
        }
        return removed;
    }

 }
   
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        OKCancelButtons()                             //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    private JPanel OKCancelButtons() {
       JButton okButton = new JButton("OK");
       okButton.setEnabled(true);
       okButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
        	  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 createDialogButtonsUI()	  
}

Open in new window

0
 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 35200955
Try the following
public class VendorEmailDialog extends JDialog {
    //CEHJ
    	final SortingListModel model = new SortingListModel();

	private TCSession session = null;
	private Registry appReg = null;
	private EdiGetRequestTransmittalInfoOperation getReqOp = null;
	private EdiGetRequestTransmittalInfoOperation.TransmittalInfo reqTransInfo = null;
	private EdiProject  project = null;
	private DefaultListModel listModel;
    JLabel label;
    private JPanel centerPanel = null;
    JPanel cards;
    protected JTextField textField;
 
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                              Constructor                             //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
   
    public VendorEmailDialog(TransmittalInfo reqTransInfo,EdiProject currentProject, Dialog parent, TCSession theSession, Registry theRegistry){
    //public VendorEmailDialog(Dialog parent){       
    super(parent,"Vendor Email Dialog", true);
	       session = theSession;
	       appReg = theRegistry;
	       project = currentProject;
	       createDialog();
	} // end constructor
    
     
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             createDialog()                           //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

    //CEHJ
    public SortingListModel getModel() {
	return model;
    }
    private void createDialog() {
    	
    	Component listPanel = EmailList();
    	Component buttonPanel = OKCancelButtons();
    	    	
    	centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
        centerPanel.setPreferredSize(new Dimension(600, 200));

        centerPanel.add(Box.createRigidArea(new Dimension(5, 0)));
        centerPanel.add(listPanel);
        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()
   
      
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             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
    }
   
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             Validating Email                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    public boolean isValidEmailAddress(String emailAddress){  
    String  expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";  
    CharSequence inputStr = emailAddress;  
    Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);  
    Matcher matcher = pattern.matcher(inputStr);  
    return matcher.matches();  
 
    }      

    
    
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                             EmailList()                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    private JPanel EmailList(){
    	 
    	final JTextField addEmail = new JTextField(20);
    	ArrayList arrayList = new ArrayList();
    	JLabel eLabel = new JLabel("Additional Emails");
    	JLabel ListLabel = new JLabel("Existing Vendor Emails");
    	
    	String[] emails = project.getEmailAddresses();	    	
    	
    	
    	for (int i = 0; i < emails.length; ++i) {
         	//listModel.addElement( emails[i]);       	
              model.addElement(emails[i]);      
        }    	    	
               
        final JList AltList = new JList(model);
    	AltList.setBorder(BorderFactory.createLoweredBevelBorder());
    	AltList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    	AltList.setLayoutOrientation(JList.VERTICAL);
    	AltList.setVisibleRowCount(4);
    	JScrollPane acrossScrollBar= new JScrollPane(AltList); 
     	
    	// addButton Code //
    	
    	final JButton addButton = new JButton("Add >>");
    	//addButton.setBackground(Color.green);
    	//addButton.setForeground(Color.green); 
    	addButton.setEnabled(true);
        addButton.addActionListener(new ActionListener() {
        
        public void actionPerformed(ActionEvent e) {
           String name = addEmail.getText();
           
             
           if(isValidEmailAddress(name)) {  
        		  
        		   //User didn't type in a unique name...
        	   Component object = null;
        	   if (name.equals("") || alreadyInList(name)) {
        		   Toolkit.getDefaultToolkit().beep();
        		   JOptionPane.showMessageDialog(object,name + "Email Address Already In List");
        		   addEmail.requestFocusInWindow();
        		   addEmail.selectAll();
        		   return;
        	   }

        	   int index = AltList.getSelectedIndex(); //get selected index
        	   if (index == -1) { //no selection, so insert at beginning
        		   index = 0;
        	   } 
        	   else {           //add after the selected item
                  index++;
        	   }

        	   //listModel.insertElementAt(addEmail.getText(), index);
        	   model.addElement(addEmail.getText());
        	   //If we just wanted to add to the end, we'd do this:
        	   //listModel.addElement(employeeName.getText());
       		   //Reset the text field.
       		   addEmail.requestFocusInWindow();
       		   addEmail.setText("");
       		   //Select the new item and make it visible.
       		   AltList.setSelectedIndex(index);
       		   AltList.ensureIndexIsVisible(index);
       	   }
       	   else{  
       		   Component object = null;
       		   JOptionPane.showMessageDialog(object,name + "Is not valid Email Address");
       		   //addEmail.requestFocusInWindow();
       		   //addEmail.setText("");
       		  
       	   }  
        }
        

           //This method tests for string equality. You could certainly
           //get more sophisticated about the algorithm.  For example,
           //you might want to ignore white space and capitalization.
           protected boolean alreadyInList(String name) {
               return model.contains(name);
           }

           //Required by DocumentListener.
           public void insertUpdate(DocumentEvent e) {
               enableButton();
           }

           //Required by DocumentListener.
           public void removeUpdate(DocumentEvent e) {
               handleEmptyTextField(e);
           }

           //Required by DocumentListener.
           public void changedUpdate(DocumentEvent e) {
               if (!handleEmptyTextField(e)) {
                   enableButton();
               }
           }

           private void enableButton() {
               if (!alreadyEnabled) {
                   addButton.setEnabled(true);
               }
           }

           private boolean handleEmptyTextField(DocumentEvent e) {
               if (e.getDocument().getLength() <= 0) {
                   addButton.setEnabled(false);
                   alreadyEnabled = false;
                   return true;
               }
               return false;
           } 
                  
           });
        
        // removeButton //
        
        final JButton removeButton = new JButton("Remove <<");
        //removeButton.setBackground(Color.red);
        //removeButton.setForeground(Color.red); 
        removeButton.setPreferredSize(new Dimension(100, 40));
        removeButton.setEnabled(true);
        removeButton.addActionListener(
        new ActionListener() {
           public void actionPerformed( ActionEvent event )
          {
        	   int index = AltList.getSelectedIndex();
               //listModel.remove(index);
        	   Object str = model.getElementAt(index);
        	    
               model.removeElement(str);
               int size = model.getSize();

               if (size == 0) { //Nobody's left, disable firing.
                   removeButton.setEnabled(false);

               } else { //Select an index.
                   if (index == model.getSize()) {
                       //removed item in last position
                       index--;
                   }

                   AltList.setSelectedIndex(index);
                   AltList.ensureIndexIsVisible(index);
               }   
          }           
         });
        
        
        
        JPanel p = new JPanel();
        //p.setBorder(BorderFactory.createLineBorder(Color.blue));
        GridBagLayout gridbag = new GridBagLayout();
        p.setLayout(gridbag);
        
        gbc.insets = new Insets(5,10,10,5);      
        set_gbc(0, 0, 1, 1,GridBagConstraints.BOTH );
        gridbag.setConstraints(eLabel, gbc);
        p.add(eLabel);
        
        set_gbc(0, 2, 1, 1,GridBagConstraints.BOTH );
        gridbag.setConstraints(ListLabel, gbc);
        p.add(ListLabel);
               
        set_gbc(1, 0, 1, 1,GridBagConstraints.HORIZONTAL);
        gridbag.setConstraints(addEmail, gbc);
        p.add(addEmail);
                
        set_gbc(1, 2, 1, 3, GridBagConstraints.HORIZONTAL);
        gbc.anchor = GridBagConstraints.PAGE_END; //bottom of space
        gbc.weightx = 3.0;
        gridbag.setConstraints(acrossScrollBar, gbc);
        p.add(acrossScrollBar);
        
        
        set_gbc(1, 1, 1, 1,GridBagConstraints.BOTH);
        gridbag.setConstraints(addButton, gbc);
        p.add(addButton);
        
        set_gbc(2, 1, 1, 1, GridBagConstraints.BOTH);
        gridbag.setConstraints(removeButton, gbc);
        p.add(removeButton);
                                    
        return p;
 }

//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        SortingListModel                              //
//                                                                      //
//////////////////////////////////////////////////////////////////////////  
    
    public class SortingListModel extends AbstractListModel
    {
    	TreeSet model;
        
    	private Comparator USEFUL_COMPARATOR = new Comparator()
            {
                public int compare( Object o1, Object o2 )
                {
                    String str1 = o1.toString();
                    String str2 = o2.toString();
                    Collator collator = Collator.getInstance();
                    int result = collator.compare( str1, str2 );
                    return result;
                }
            };

    public SortingListModel()
    {
        model = new TreeSet( USEFUL_COMPARATOR );
    }

    // ListModel methods
    public int getSize()
    {
        // Return the model size
        return model.size();
    }

    public Object getElementAt( int index )
    {
        // Return the appropriate element
        return model.toArray()[index];
    }

    // Other methods
    public void addElement( Object element )
    {
        
        if( model.add( element ))
        {
            fireContentsChanged( this, 0, getSize() );
        }
    }

    public void addAll( Object elements[] )
    {
        Collection c = Arrays.asList(elements);
        model.addAll(c);
        fireContentsChanged( this, 0, getSize() );
    }

    public void clear()
    {
        model.clear();
        fireContentsChanged( this, 0, getSize() );
    }

    public boolean contains( Object element )
    {
        return model.contains( element );
    }

    public Object firstElement()
    {
        // Return the appropriate element
        return model.first();
    }

    public Iterator iterator()
    {
        return model.iterator();
    }

    public Object lastElement()
    {
        // Return the appropriate element
        return model.last();
    }

    public boolean removeElement( Object element )
    {
        boolean removed = model.remove( element );
        if( removed )
        {
            fireContentsChanged( this, 0, getSize() );
        }
        return removed;
    }

 }
   
//////////////////////////////////////////////////////////////////////////
//                                                                      //
//                        OKCancelButtons()                             //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
    
    private JPanel OKCancelButtons() {
       JButton okButton = new JButton("OK");
       okButton.setEnabled(true);
       okButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
        	  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 createDialogButtonsUI()	  
}

Open in new window

0
 

Author Comment

by:jkteater
ID: 35201189
looks good - thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35201293
:)
0

Featured Post

What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question