I'm writing a graphics editor. Some components is displayed on a pane of editor. They must react on a mouse clicks. At the same time the pane of editor must react on a clicks too. For example, we have two buttons on a pane. We click on a first button and the button will change its displaying (will look as launched). Then we click on a second button and it will do the same. And at the same time the pane of editor will draw line from first button to second button.
Here is my test code. I set my pane of editor as a glass pane and added a listener to it. I added my buttons to a content pane and added a listener to a top button. When I click on the top button, i will see that the pane's listener process, but the button's listener will not process and not change its displaying!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame {
public Test() {
super("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 200);
JButton bottomBtn = new JButton("On bottom");
bottomBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("JButton.mouseClicked()");
}
});
JButton topBtn = new JButton("On top");
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(bottomBtn, "South");
contentPane.add(topBtn, "North");
setContentPane(contentPane);
ControlPanel control = new ControlPanel();
setGlassPane(control);
setVisible(true);
control.setVisible(true); // is there any other way?
}
public static void main(String[] args) {
new Test();
}
private class ControlPanel extends JComponent implements MouseListener {
public ControlPanel() {
setOpaque(false);
addMouseListener(this);
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("ControlPanel.mouseClicked()");
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
}