rikb
rikb

Reputation: 572

JList MouseMoved and MousePressed

I've extended a JList to provide two separate functionalities, toolTipText for items, and right-click options. Both work separately, but when I try to use them together, the MouseMoved events aren't being recognized? Below are the guts of my new listener methods. How should I be negotiating these various events?

public class JListTT extends javax.swing.JList {
    public JListTT() {
        super();
       addMouseListener(new ttListener());
...
   class ttListener extends MouseAdapter {
        public void mouseMoved(MouseEvent e) {
             String nodeID = bldItemNodeID();
             theList.setToolTipText(nodeID);
            }
        public void mousePressed(MouseEvent ev)  {check(ev); }
        public void mouseReleased(MouseEvent ev) {check(ev); }
        public void mouseClicked(MouseEvent ev)  {check(ev); }
        public void check(MouseEvent ev) {
            if (ev.isPopupTrigger()) { 
                theList.setSelectedIndex(theList.locationToIndex(ev.getPoint())); 
                menu.show(theList, ev.getX(), ev.getY()); 
            }
        }
    }

Upvotes: 3

Views: 1716

Answers (4)

Lay Leangsros
Lay Leangsros

Reputation: 9296

You can achieve it by using mouseDragged

YourClass extends JPanel implements MouseListener{
    ......

    @Override
    public void mouseDragged(MouseEvent e) {
        //code go here

    }
}

Upvotes: 0

kleopatra
kleopatra

Reputation: 51536

there's not necessarily a need for a low-level approach as a custom mouse-/motionListener:

  • as to a per-cell tooltip, see @Robin's answer
  • as to a context menu, JComonent has a property componentPopupMenu: using that will cope with opening the menu on keyboard short-cut automatically

"not necessarily" because you seem to rely on the cell being selected on right click. If so, you would still need a MouseListener to trigger the selection (after decade long debates, Swing doesn't - which seems to be unusual in current native apps ;-)

Upvotes: 1

Robin
Robin

Reputation: 36621

I did not test this myself, but looking at the javadoc of JList the tooltip functionality is available out of the box. The javadoc of JList#getTooltipText clearly states

Overrides JComponent's getToolTipText method in order to allow the renderer's tips to be used if it has text set.

So if your ListCellRenderer returns a Component in the getListCellRendererComponent method which has a tooltip it will be displayed by the JList without the need of a listener.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

You add the ttListener object as a MouseListener, but I don't see you adding the ttListener object as a MouseMotionListener. For example:

ttListener myMouseadapter = new ttListener();
addMouseListener(myMouseadapter);
addMouseMotionListener(myMouseadapter);

Upvotes: 4

Related Questions