-3

I have been programming the following code and I've been unable to get double clicks on a JScrollPane. This is the code I have: my code

However, Using this throws an error: that JScrollPanes cannot be cast to JLists. Additionally, this occurs when clicking the table and not the cells itself. Im really unsure of how to get an action listener onto the JScrollPane that reacts to when i click the cells. Does anyone have any ideas?

Orion
  • 25
  • 3

1 Answers1

0

Mouse events are passed to the component that you click on.

If that component does not have a mouse listener, then the event is passed up to the parent component until a component with a mouse listener is found.

By default a Swing adds a MouseListener to a JList (for example to handle the clicking on an item in the list), so the event will never be passed to the scroll pane.

Additionally, this occurs when clicking the table and not the cells itself.

Don't know what this means. What is the "table" and what are the "cells"? It sounds like you are adding a JTable to the scroll pane, not a JList.

In any case, if you want to listen for mouse events on a JList (which has been added to the viewport of the scrollPane), then you need to add the MouseListener to the JList. So the basic code is something like:

JList list = new JList(...);
list.addMouseListener(...);
JScrollPane scrollPane = new JScrollPane( list );
frame.add( scrollPane );

Now in your MouseListener the source of the MouseEvent will be the JList.

Also note than in your listener you can then get the value of the selected item directly from the JList:

JList list = (JList)mouseEvent.getSource();
System.out.println( list.getSelectedValue() );
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Oh, wait. Yea, I'm populating with a JTable. Is there a way this code can be used to click on cells inside a JScrollTable? – Orion Nov 21 '19 at 04:08
  • @Orion, don't forget to "accept" the answer by clicking on the checkmark so people know the problem has been solved. – camickr Nov 22 '19 at 18:56