具有边框布局的 JPanel 上的事件
当我将 MouseListener/FocusListener 添加到其中包含 BorderLayout 和 JComponent 的 JPanel 时,我无法捕获鼠标或焦点事件。有没有办法捕获具有 BorderLayout 的 JPanel 鼠标和焦点事件?
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);
}
}
When I add a MouseListener/FocusListener to a JPanel 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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如所说,只是一个简单的错误。由于
JFrame
被赋予了FlowLayout
,因此JPanel
仅占据JButton
所需的区域。您可以通过向JPanel
添加Border
来测试这一点。现在可以了,
As said, just a simple mistake. Because
JFrame
is given aFlowLayout
, theJPanel
occupies the area required forJButton
only. You can test that by adding aBorder
to theJPanel
.Now it works,
以下代码将相应的事件打印到 StdOut。
The following Code prints the corresponding Events to StdOut.