?
Solved

Array to Jist to Array

Posted on 2011-10-06
16
Medium Priority
?
293 Views
Last Modified: 2012-06-27
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?
0
Comment
Question by:jkteater
  • 7
  • 6
  • 3
16 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 36927468
Java ListModel is really broken for collections. Try

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

Expert Comment

by:for_yan
ID: 36927471


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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36927474
Otherwise just create a new List and iterate the ListModel, adding again
0
Technology Partners: 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!

 
LVL 47

Expert Comment

by:for_yan
ID: 36927478
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36927484
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36927681
>>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
 

Author Comment

by:jkteater
ID: 36931110
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36931146
Use the code above to get array back from ListModel
0
 

Author Comment

by:jkteater
ID: 36931170
I did try the code - but it still was not updating the array for some reason
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36931218
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36931246
That's difficult to understand.
Do you see the list updated?
Put System.out.println(..) As you retrieve each element from listModel
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36931329
>>That's difficult to understand.

What's difficult to understand?
0
 
LVL 47

Accepted Solution

by:
for_yan earned 400 total points
ID: 36931361


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
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 36931441
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
 

Author Comment

by:jkteater
ID: 36932939
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36932948
Good, it works!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month13 days, 16 hours left to enroll

809 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