JList Problem
When I click a Jlist which is inside a JScrollPane, I want the selection to be copied to a JTextArea. Problem is, it copies twice every time! It seems it copies once for mouse press and once for mouse release. I thought the ActionListener would just see the mouse click event. Anybody any ideas?
I have already added the ListSelectionListener - see code snippets below:
locationList.addListSelectionListener(this);
public void valueChanged(ListSelectionEvent event)
{
JList source = (JList)event.getSource();
String aselection = "";
if(source == locationList)
{
bookDetails.append("Now enter a Bay No...");
aselection = (String)locationList.getSelectedValue();
aplace = new Location();
aplace.setArea(aselection);
bookDetails.append(aplace.getArea() + "\n");
}
}// End of valueChanged method
The text area is bookDetails and the append method appends the text on to the text area - but it appends it twice - even for one mouse click. Even if I put the append method outside the if statement, it still goes in twice.
That's because you get to valueChanged events...one for the previous item being de-selected, and teh new one being selected. What you really want to do is on the change event, call the getSelectedItem method to return the object ... typcast to string....etc...
The othe way is to use the mouse listener, this will print on dubleclick,
jlist.addMouseListener(new MouseAdapter()
{public void mousePressed(MouseEvent m)
{
if (m.getClickCount() == 2)
{
int index = jlist.locationToIndex(m.getPoint());
System.out.println("Double clicked on Item " + index);
}
}
});