Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 509
  • Last Modified:

A JList Box Question

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
prain
Asked:
prain
1 Solution
 
terajivCommented:
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
 
mwibbelsCommented:
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
 
funduraghuCommented:
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
 
prainAuthor Commented:
I Thank all who gave their views and comments to thhos question.

However, funduraguh gave the perfect answer.

Good Job fundu.
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.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

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