Mouse Listener Problem...

Hey all... I'm having probelms with mouse listeners.

I have a JPanel (mainJPanel) that has a gridlayout (2, 2). To this I have added a mouse listener that gets the position of the mouse in this panel. To mainJPanel, I'm adding four JPanels (subPanels, were i is 0 - 3). Now I wanted to add mouse listeners to the four sub-panels so I can get which sub-panel the mouse is over. But when ever I add the mouse listeners to the sub-panels the mouse listener for the mainJPanel stops working. Can anybody tell me what I'm doing wrong and how I can resolve this problem.

Thanx in advance...

[606 byte] By [G-Rehukua] at [2007-10-1 22:10:59]
# 1

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class MouseTargets extends JPanel

{

JLabel label;

public MouseTargets()

{

setLayout(new GridLayout(2,0));

for(int j = 0; j < 4; j++)

{

JPanel panel = new JPanel();

panel.setBorder(BorderFactory.createEtchedBorder());

add(panel);

}

addMouseMotionListener(new PanelListener());

}

private class PanelListener extends MouseMotionAdapter

{

JComponent lastEntered;

public PanelListener()

{

// initialize lastEntered to parent component

lastEntered = MouseTargets.this;

}

public void mouseMoved(MouseEvent e)

{

JPanel parent = (JPanel)e.getSource();

Point p = e.getPoint();

JComponent target = (JComponent)getContainingPanel(p, parent);

if(lastEntered != target)

{

target.setBorder(BorderFactory.createLineBorder(Color.red));

lastEntered.setBorder(BorderFactory.createEtchedBorder());

lastEntered = target;

}

label.setText("x = " + p.x + " y = " + p.y);

}

private Component getContainingPanel(Point p, Component parent)

{

Component[] c = getComponents();

for(int j = 0; j < c.length; j++)

{

Rectangle r = c[j].getBounds();

if(r.contains(p))

return c[j];

}

// if no child components contain the point

// return the parent container

return parent;

}

}

private JLabel getLabel()

{

label = new JLabel();

label.setHorizontalAlignment(JLabel.CENTER);

Dimension d = label.getPreferredSize();

d.height = 35;

label.setPreferredSize(d);

return label;

}

public static void main(String[] args)

{

MouseTargets test = new MouseTargets();

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(test);

f.getContentPane().add(test.getLabel(), "South");

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

}

74philipa at 2007-7-13 8:24:25 > top of Java-index,Archived Forums,Java 2 Software Development Kit (J2SE SDK)...
# 2
Or see SwingUtilities.getDeepestComponent
tjacobs01a at 2007-7-13 8:24:25 > top of Java-index,Archived Forums,Java 2 Software Development Kit (J2SE SDK)...