Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

A JList Box Question

Posted on 2000-04-27
4
Medium Priority
?
504 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 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone 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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
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 will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month10 days, 18 hours left to enroll

571 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