?
Solved

A JList Box Question

Posted on 2000-04-27
4
Medium Priority
?
486 Views
Last Modified: 2008-03-10
Below is a JList Box Testing program. Please compile the two files, TEST.java and then the SortedListModel.java files and then run the program. DO these steps.

1. Enter a number or anything string.
2. Click the "Click Button". You will see the the string you entered in the TextField is noe appearing in the JListBox.
3. Click the ListBox item. You will receive a message.
4. Close the message.
5. Now click the ListBox item again.
This time the MessageBox does not appear.

WHY IS THAT?

Can anyone fix the problem in the given code?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;
 
 public class TEST  extends JDialog implements
  ActionListener, ListSelectionListener, ItemListener{
             
   JButton buttonOK, buttonTest;
   JTextField aTextField;
   JLabel aLabel, anotherLabel;
   JList aList;
   final SortedListModel model;
 

   DataBase localDb;

   public  TEST  (JFrame Parent)
   {
      // call base class constructor
      super(Parent, "TESTING", true);
      setSize( 600, 325 );

      GridBagLayout gbl = new GridBagLayout();
     
      GridBagConstraints gbc = new GridBagConstraints();  
 
      JPanel pInputPanel = new JPanel();
      pInputPanel.setBorder(new TitledBorder("Enter Information"));

      pInputPanel.setLayout(gbl);

      //======================First Panel============================
      //Adding Row 1
      gbc.anchor = GridBagConstraints.WEST;
      gbc.weightx = 5;
      gbc.weighty = 5;

      gbc.gridx = 0;
      gbc.gridy = 0;
      gbl.setConstraints(aLabel = new JLabel("Enter a Number :"), gbc);
      pInputPanel.add(aLabel);

      gbc.gridx = 1;
      gbc.gridy = 0;
      gbl.setConstraints(aTextField = new JTextField(10), gbc);
      pInputPanel.add(aTextField);  

      gbc.gridx = 2;
      gbc.gridy = 0;
      gbl.setConstraints(buttonTest = new JButton("Click Button"), gbc);
      buttonTest.addActionListener(this);
      pInputPanel.add(buttonTest);  

      getContentPane().add(pInputPanel, BorderLayout.NORTH);
     
      //========================Second Panel===========================
      JPanel listPanel = new JPanel();
      listPanel.setBorder(new TitledBorder(""));
      listPanel.setLayout(new FlowLayout());

      model = new SortedListModel();
      aList = new JList(model);
      aList.setVisibleRowCount(6);
      aList.setFixedCellWidth(500);
      aList.setValueIsAdjusting(true);
      aList.addListSelectionListener(this);
      aList.setSelectedIndex(0);

      JScrollPane jsp = new JScrollPane(aList);
      listPanel.add(jsp);

      gbl.setConstraints(anotherLabel =
           new JLabel("Click a List Item Above to See a Message"), gbc);
      listPanel.add(anotherLabel);


      getContentPane().add(listPanel, BorderLayout.CENTER);

      //========================Third Panel============================
      JPanel aButtonPanel = new JPanel();
      aButtonPanel.setLayout(new FlowLayout());
      buttonOK = new JButton ("   OK   ");
      buttonOK.addActionListener(this);
      aButtonPanel.add(buttonOK);
     
      getContentPane().add(aButtonPanel, BorderLayout.SOUTH);
   }

   public void actionPerformed (ActionEvent e )
   {
     if(e.getSource() == buttonOK)
           dispose();

     
     if(e.getSource() == buttonTest)
     {
      model.clear();
      model.add( aTextField.getText());
     }
   }

   public void itemStateChanged(ItemEvent e)
   {

   }

   public void valueChanged(ListSelectionEvent e)
   {
    if(!e.getValueIsAdjusting())
    {
     if(e.getSource() == aList)
     {
        JOptionPane.showMessageDialog(this, "Just A Message", "Testing",
                                      JOptionPane.ERROR_MESSAGE);    

     }
    }
   }

   public static void main (String [] args)
   {
     TEST tst = new TEST(null);
     tst.setVisible(true);
   }

}







import javax.swing.*;import java.util.*;

public class SortedListModel extends AbstractListModel
{  // Define a SortedSet
  SortedSet model;  
  public SortedListModel()
  {// Create a TreeSet
   // Store it in SortedSet variable    
   model = new TreeSet();  
  }
 
  // ListModel methods  
  public int getSize()
  {// Return the model size
    return model.size();
  }

 //isEmpty
 public boolean isEmpty()
 {
  if(getSize() > 0)
   return false;
 
  return true;
 }  
 public Object[] getAllElements()
 {
  return model.toArray();
 }

 public Object getElementAt(int index)
  {
   // Return the appropriate element    
   return model.toArray()[index];
  }
 
  // Other methods  
  public void add(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 addVector(Vector vctr)
  {
   int length = vctr.size();

   for (int i = 0; i < length; i++)
     add(vctr.get(i));
   
  }
 


  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;    
  }
}






0
Comment
Question by:prain
[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
4 Comments
 
LVL 3

Expert Comment

by:terajiv
ID: 2758082
Hi prain,

Why dont u use Dialog class instead of

JOptionPane.showMessageDialog(this, "Just A Message", "Testing",
                                      JOptionPane.ERROR_MESSAGE);    

I think that can be the problem... because I have faced the same kind of problem I changed the class to Dialog and I started getting messages correctly.

Just try it.. This may work for u too...

Have A Nice Time...
And All the Best

Rajiv
0
 
LVL 2

Expert Comment

by:mwibbels
ID: 2758641
It's because you're listening to selection events. Once you click on the element, it is selected *and stays selected*. So any subsequent clicks won't do anything.

To show you, change your SortedListModel:

public void clear() {
    int size = getSize();
    if (size > 0) {
        model.clear();
        // generate correct event (was fireContentChanged(..))
        fireIntervalRemoved(this, 0, size-1);
    }
}

Now do the following:
1) add an item to the list
2) click on it -> message (cause first selection)
3) click on it again -> no message
4) add a new item. the new code will cause the ListSelectionModel to reset the selection
5) click on it -> message (cause first selection)
6) click on it again -> no message

Does this explain it to you?
0
 

Accepted Solution

by:
funduraghu earned 400 total points
ID: 2758781
Hi prain,

I think u want the dialog to come up whenever anyone clicks on the list.
The ListSelectionEvent.valueChanged() is called only when the selection in the JList box changes.
Hence, the first time anyone clicks on the list, the selection changes, as by default no item is selected.
The next time anyone clicks on the same item, the selection is not changed and hence, the valueChanged() is not called.

If u want to display the dialogbox everytime any user clicks on the list item,
u need to use mouselistener

Below is the modified code :

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;
 
 public class TEST  extends JDialog implements
  ActionListener, ListSelectionListener, ItemListener, MouseListener{
             
   JButton buttonOK, buttonTest;
   JTextField aTextField;
   JLabel aLabel, anotherLabel;
   JList aList;
   final SortedListModel model;

   
   DataBase localDb;

   public  TEST  (JFrame Parent)
   {
      // call base class constructor
      super(Parent, "TESTING", true);
      setSize( 600, 325 );

      GridBagLayout gbl = new GridBagLayout();
       
      GridBagConstraints gbc = new GridBagConstraints();  
   
      JPanel pInputPanel = new JPanel();
      pInputPanel.setBorder(new TitledBorder("Enter Information"));

      pInputPanel.setLayout(gbl);

      //======================First Panel============================
      //Adding Row 1
      gbc.anchor = GridBagConstraints.WEST;
      gbc.weightx = 5;
      gbc.weighty = 5;

      gbc.gridx = 0;
      gbc.gridy = 0;
      gbl.setConstraints(aLabel = new JLabel("Enter a Number :"), gbc);
      pInputPanel.add(aLabel);

      gbc.gridx = 1;
      gbc.gridy = 0;
      gbl.setConstraints(aTextField = new JTextField(10), gbc);
      pInputPanel.add(aTextField);  

      gbc.gridx = 2;
      gbc.gridy = 0;
      gbl.setConstraints(buttonTest = new JButton("Click Button"), gbc);
      buttonTest.addActionListener(this);
      pInputPanel.add(buttonTest);  

      getContentPane().add(pInputPanel, BorderLayout.NORTH);
       
      //========================Second Panel===========================
      JPanel listPanel = new JPanel();
      listPanel.setBorder(new TitledBorder(""));
      listPanel.setLayout(new FlowLayout());

      model = new SortedListModel();
      aList = new JList(model);
      aList.setVisibleRowCount(6);
      aList.setFixedCellWidth(500);
      aList.setValueIsAdjusting(true);
//      aList.addListSelectionListener(this);
                  aList.addMouseListener(this);
      aList.setSelectedIndex(0);

      JScrollPane jsp = new JScrollPane(aList);
      listPanel.add(jsp);

      gbl.setConstraints(anotherLabel =
           new JLabel("Click a List Item Above to See a Message"), gbc);
      listPanel.add(anotherLabel);


      getContentPane().add(listPanel, BorderLayout.CENTER);

      //========================Third Panel============================
      JPanel aButtonPanel = new JPanel();
      aButtonPanel.setLayout(new FlowLayout());
      buttonOK = new JButton ("   OK   ");
      buttonOK.addActionListener(this);
      aButtonPanel.add(buttonOK);
       
      getContentPane().add(aButtonPanel, BorderLayout.SOUTH);
   }

   public void actionPerformed (ActionEvent e )
   {
     if(e.getSource() == buttonOK)
           dispose();

     
     if(e.getSource() == buttonTest)
     {
      model.clear();
      model.add( aTextField.getText());
     }
   }

   public void itemStateChanged(ItemEvent e)
   {

   }

   public void valueChanged(ListSelectionEvent e)
   {
    if(!e.getValueIsAdjusting())
    {
     if(e.getSource() == aList)
     {
        JOptionPane.showMessageDialog(this, "Just A Message", "Testing",
                                      JOptionPane.ERROR_MESSAGE);      

     }
    }
   }
   
  public void mouseClicked(MouseEvent e) {
      if(e.getSource() == aList){
                              //Gets the selected item in the list box
                              int index = aList.locationToIndex(e.getPoint());
                  JOptionPane.showMessageDialog(this, "Just A Message", "Testing",
                                                    JOptionPane.ERROR_MESSAGE);      
      }
     }

      public void mouseReleased(MouseEvent e){
      }
      public void mouseEntered(MouseEvent e){
      }
      public void mousePressed(MouseEvent e){
      }
      public void mouseExited(MouseEvent e){
      }
            
   public static void main (String [] args)
   {
     TEST tst = new TEST(null);
     tst.setVisible(true);
   }
}

Now try the same steps & u would see the desired output.

I hope this helps

Regards,
funduraghu
0
 

Author Comment

by:prain
ID: 2759192
I Thank all who gave their views and comments to thhos question.

However, funduraguh gave the perfect answer.

Good Job fundu.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
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…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

719 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