i dont how to solve this problem. I am developing a graphical editor, where arc(line) drawing is possible. I manually set the size of arc component to 1000x1000, so i dont
I tried two ways to forvard events to several components. The first way is to redispatch events from a GlassPane
to all components wich appears under it. The second way is to use global even listener AWTEventListener
Here is the code of the first way. Note if your GlassPane
has other size as opposed to ContentPane
you will need to convert coordinates of mouse cursor (I don't know but I thin the convertPoint(...)
method is pertinent).
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame {
public Test() {
super();
JButton testBtn = new JButton("Test");
testBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Button's MouseEvent");
}
});
add(testBtn, BorderLayout.SOUTH);
ControlPanel control = new ControlPanel(getContentPane());
setGlassPane(control);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 200);
setVisible(true);
control.setVisible(true);
}
private class ControlPanel extends JComponent {
private Container underControl;
public ControlPanel(Container underControl) {
this.underControl = underControl;
// Instead settig some listeners.
// If any listeners doesn't set, any events will not process
enableEvents(MouseEvent.MOUSE_EVENT_MASK);
setOpaque(false);
}
@Override
public void processMouseEvent(MouseEvent e) {
// do something
redispatchMouseEvent(e);
}
private void redispatchMouseEvent(MouseEvent e) {
System.out.println("redispatchMouseEvent()");
Component[] components = underControl.getComponents();
for(Component c : components) {
if(c.getBounds().contains(e.getX(), e.getY())) {
e = SwingUtilities.convertMouseEvent(underControl, e, c);
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(e);
}
}
}
}
public static void main(String[] args) {
new Test();
}
}
And here is the second way.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.MouseInputAdapter;
public class Test extends JFrame {
public Test() {
super();
JButton btn = new JButton("Test");
btn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("JButton.onMouseClicked()");
}
});
add(btn, "South");
long eventMask = AWTEvent.MOUSE_MOTION_EVENT_MASK;
Toolkit.getDefaultToolkit().addAWTEventListener(
new AWTEventListener() {
public void eventDispatched(AWTEvent e) {
System.out.println(e.getID());
if(e.getID() == MouseEvent.MOUSE_DRAGGED) {
System.out.println("Dragged");
}
if(e.getSource() instanceof JButton) {
System.out.println("Under the button");
}
}
},
eventMask
);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}