Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Events on a JPanel which has a Border Layout

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

}
like image 410
MOD Avatar asked Oct 27 '25 03:10

MOD


1 Answers

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);
            }
        });
    }
}
like image 168
mKorbel Avatar answered Oct 29 '25 17:10

mKorbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!