Solved

A JList Box Question

Posted on 2000-04-27
4
434 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
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 100 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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

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.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

708 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now