When I add a MouseListener/FocusListener to a J开发者_开发知识库Panel which has a BorderLayout and JComponents in it, I can't catch mouse or focus events. Is there any way to catch a JPanel's mouse and focus events which has a BorderLayout?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Application extends JFrame{
public Application(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel(new BorderLayout());
jPanel.add(new JButton("Button"));
jPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
});
// if border is set then listener works if not does not
// jPanel.setBorder(new LineBorder(Color.black, 1));
setLayout(new FlowLayout());
add(jPanel);
setSize(400, 400);
setVisible(true);
}
public static void main(String[]args){
new Application().setVisible(true);
}
}
As said, just a simple mistake. Because JFrame
is given a FlowLayout
, the JPanel
occupies the area required for JButton
only. You can test that by adding a Border
to the JPanel
.
Now it works,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Application extends JFrame {
private static final long serialVersionUID = 1L;
public Application() {
JPanel jPanel = new JPanel();
jPanel.setLayout(new FlowLayout());
jPanel.add(new JButton("Button"));
jPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(jPanel);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Application().setVisible(true);
}
});
}
}
The following Code prints the corresponding Events to StdOut.
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JPanel innerPanel = new JPanel();
innerPanel.setSize(200,200);
panel.add(innerPanel);
panel.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
System.out.println("MouseReleased");
}
public void mousePressed(MouseEvent e) {
System.out.println("MousePressed");
}
public void mouseExited(MouseEvent e) {
System.out.println("MouseExited");
}
public void mouseEntered(MouseEvent e) {
System.out.println("MouseEntered");
}
public void mouseClicked(MouseEvent e) {
System.out.println("MouseClicked");
}
});
frame.setContentPane(panel);
frame.setVisible(true);`
精彩评论