java-具有边框布局的JPanel上的事件

当我向其中具有BorderLayout和JComponents的JPanel添加MouseListener / FocusListener时,我无法捕获鼠标或焦点事件.有什么方法可以捕获具有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);
    }

}
最佳答案
如前所述,只是一个简单的错误.由于为JFrame提供了FlowLayout,因此JPanel仅占用JButton所需的区域.您可以通过向JPanel添加边框来进行测试.

现在可以了,

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);
            }
        });
    }
}

转载注明原文:java-具有边框布局的JPanel上的事件 - 代码日志