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?

[309 byte] By [johnjsmith] at [2007-9-27 4:44:46]
# 1
Try this:addListSelectionListener(ListSelectionListenerlistener) Adds a listener to the list that's notified each time a change to the selection occurs
noah.w at 2007-7-5 14:36:35 > top of Java-index,Archived Forums,Java Programming...
# 2

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.

johnjsmith at 2007-7-5 14:36:35 > top of Java-index,Archived Forums,Java Programming...
# 3
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...
smg123 at 2007-7-5 14:36:35 > top of Java-index,Archived Forums,Java Programming...
# 4

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

}

}

});

noah.w at 2007-7-5 14:36:35 > top of Java-index,Archived Forums,Java Programming...
# 5
getSelectedItem is not a valid method for JList !Fixed it myself.
johnjsmith at 2007-7-5 14:36:35 > top of Java-index,Archived Forums,Java Programming...
# 6
Tried this and couldn't get it to compile - abstract class.Fixed it myself using different approach.Thanks for the replies.
johnjsmith at 2007-7-5 14:36:35 > top of Java-index,Archived Forums,Java Programming...
# 7
How did you fix it ?Noah
noah.w at 2007-7-5 14:36:35 > top of Java-index,Archived Forums,Java Programming...