Array to Jist to Array

I pull a array - put it in a listmodel make changes and need to change the listmodel back to the array.
What you dont see in the code below is that I add and remove elements in the method

emails = project.getEmailAddresses();  my String array
listModel = new DefaultListModel();
    	
        for (int i = 0; i < emails.length; ++i) {
         	listModel.addElement( emails[i]);       	
        }    	    	
               
        final JList AltList = new JList(listModel);

Open in new window


But when I am finsihed - how do take the changes and put back in to the array?
jkteaterAsked:
Who is Participating?
 
for_yanCommented:


Try this and look what is the output.
If you see that the list is different, this should give you different array:

listModel = AtList.getModel();
String [] array = new String[listModel.getSize()]
for (int j= 0; j<listModel.getSize(); j++){

array[j] = (String) listModel.getElementAt(j);
System.out.println(array[j]);
}

Open in new window

0
 
CEHJCommented:
Java ListModel is really broken for collections. Try

http://technojeeves.com/joomla/index.php/free/76-collectionsnicelistmodel
0
 
for_yanCommented:


String [] array = new String[listModel.size()]
for (int j= 0; j<listModel.size(); j++){
array[j] = (String) listModel.getElementAt(j);
}

Open in new window

0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
CEHJCommented:
Otherwise just create a new List and iterate the ListModel, adding again
0
 
for_yanCommented:
Actually with list model you need to use getSize() not size()

String [] array = new String[listModel.size()]
for (int j= 0; j<listModel.getSize(); j++){
array[j] = (String) listModel.getElementAt(j);
}

Open in new window

0
 
for_yanCommented:
This is correct:

String [] array = new String[listModel.getSize()]
for (int j= 0; j<listModel.getSize(); j++){
array[j] = (String) listModel.getElementAt(j);
}

Open in new window

0
 
CEHJCommented:
>>What you dont see in the code below is that I add and remove elements in the method

Can you give some idea of what you're doing there?
0
 
jkteaterAuthor Commented:
Here are the steps in the method I am attaching below

creating a String Array emails with values from a different class
creating a listModel - adding the values from the array to the listmodel
adding and removing things from the listModel.  

after the changes I need to take the listModel ( which reflects the changes the users has made ) and update or replace the emails array with what is in the ListModel

becuase when the user clicks the done button on the dialog - I am sending the array back to the class I got it from.

okButton.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
                 project.setEmailAddresses(emails);


 
private JPanel EmailList(){
    	 
    	final JTextField addEmail = new JTextField(20);
    	emails = project.getEmailAddresses();
    	JLabel eLabel = new JLabel("Additional Emails");
    	JLabel ListLabel = new JLabel("Existing Vendor Emails");
    		    	
    	listModel = new DefaultListModel();
    	
        for (int i = 0; i < emails.length; ++i) {
         	listModel.addElement( emails[i]);       	
        }    	    	
               
        final JList AltList = new JList(listModel);
    	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);
        	  //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 listModel.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);

               int size = listModel.getSize();

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

               } else { //Select an index.
                   if (index == listModel.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;
     }

Open in new window

0
 
for_yanCommented:
Use the code above to get array back from ListModel
0
 
jkteaterAuthor Commented:
I did try the code - but it still was not updating the array for some reason
0
 
CEHJCommented:
If you use the class i gave you

a. you can put the emails into a List (more apt for deletions and additions)
b. act directly on that List
c. get the List from the model without any intervening code and send it back to the class you want to send it to
0
 
for_yanCommented:
That's difficult to understand.
Do you see the list updated?
Put System.out.println(..) As you retrieve each element from listModel
0
 
CEHJCommented:
>>That's difficult to understand.

What's difficult to understand?
0
 
CEHJCommented:
Here's a working example of what i was saying
import java.awt.event.*;
import java.awt.Container;
import java.awt.BorderLayout;

import java.util.*;

import javax.swing.*;

import net.proteanit.util.CollectionsNiceListModel;


public class FB extends JFrame implements ActionListener {
    private JButton b;
    // You'd fill it in a better way probably
    private java.util.List<String> emails = new ArrayList<String>(Arrays.asList(new String[] { "boo@far.com", "foo@bar.com", "moo@baa.com" }));
    private JList emailsList;


    public void actionPerformed(java.awt.event.ActionEvent e) {
        List mutable = (List)emailsList.getModel();
	mutable.remove(0);
	JOptionPane.showMessageDialog(this, "Following list would now be sent: " + mutable);
    }

    private void setGui() {
        try {
	    setLocation(0, 100);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            Container cp = getContentPane();
	    emailsList = new JList(new CollectionsNiceListModel<String>(emails));
	    cp.add(new JScrollPane(emailsList), BorderLayout.CENTER);
            JPanel bPanel = new JPanel();
            b = new JButton("Remove top");
            b.addActionListener(this);
            bPanel.add(b);
            cp.add(bPanel, BorderLayout.SOUTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        FB f = new FB();
                        f.setGui();
                        f.setSize(200, 200);
                        f.setVisible(true);
                    }
                });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Open in new window

0
 
jkteaterAuthor Commented:
I do appreciate all that you guys do.  CEHJ and for_yan you have help me so many times and for that I want to say thanks.  CEHJ, I do agree that the example above is probably the best way.   But I did not want to rewrite my method.  So I basically  wrote a small method to capture the updatedJList, write that to a new Array and returned the new array.  It seems to work for now.

Thanks Again
0
 
for_yanCommented:
Good, it works!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.