编程语言
首页 > 编程语言> > java-具有边框布局的JPanel上的事件

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

标签:border-layout,listener,swing,jpanel,java
来源: https://codeday.me/bug/20191202/2086949.html