Question about JPanel cover the whole area of BorderLayout when using BorderLayout.CENTER

20 Views Asked by At

I am trying to set a BorderLayout of my JFrame.

Firstly create a FlowLayout with two JButtons. Then add the FlowLayout the top of BorderLayout. It works correctly according to my code.

Secondly, I created a MyPanel object which is inherited from JPanel. There is a MouseAdapter to realize when the mouse left click panel output mouse coordinates.

Everything works fine but I found the MouseEvent will be listened and output the coordinate wherever I click the mouse except the top panel.

My question is: Wouldn't the mouse event be triggered only if I clicked on the middle part of the frame, because I added the mouse listener to MyPanel, which was added to the CENTER position of BorderLayout.

Following is my code:

import javax.swing.*;
import java.awt.event.*;
public class MyPanel extends JPanel{
    public MyPanel() {
        //anonymous class to listen mouse 
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //if left click
                if (e.getButton() == MouseEvent.BUTTON1) {
                    //print location message
                    System.out.println("Left button clicked at position (" + e.getX() + ", " + e.getY() + ")");
                }
            }
        });
    }
}
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame{
    public MyFrame() {
        //initial settings of frame
        this.setSize(400, 300);
        this.setTitle("MyFrame Title");
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //set layout of frame
        BorderLayout l1 = new BorderLayout();
        this.setLayout(l1);
        
        //set top panel
        JPanel top = new JPanel(new FlowLayout(FlowLayout.CENTER));
        //buttons in top panel
        JButton b1 = new JButton("Left");
        JButton b2 = new JButton("Right");
        //add to top of frame
        this.add(top,BorderLayout.PAGE_START);
        
        //add my panel to center of frame
        MyPanel center = new MyPanel();
        this.add(center,BorderLayout.CENTER);
        //add buttons
        top.add(b1);
        top.add(b2);
        
        //make it visible
        this.setVisible(true);
    }
}
0

There are 0 best solutions below