在Java中,我尝试使用容器类中的getComponentAt(x,y)方法。但是对于给定的(x,y)坐标,即使(x,y)包含一些image / JLabel / JButton,它也总是返回给我javax.swing.JRootPane类的对象。

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class temp2 implements MouseListener{
    public static void main(String[] arg){
        frame = new JFrame("adsa");
        frame.setBounds(0, 0, 1000, 1000);
        frame.setVisible(true);
        frame.addMouseListener(new temp2());
        JButton l = new JButton("asdasd");
        frame.add(l);
        l.addMouseListener(new temp2());;
    }
    static JFrame frame;
    @Override
    public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
            System.out.println(frame.getComponentAt(x, y).getClass());
        System.out.println(frame.getComponentAt(x, y) instanceof JButton);

    }
    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }
    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }
    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

    }
    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

    }

}


这是我用于测试的示例代码。
每当我单击按钮时,我都会得到以下输出:

class javax.swing.JRootPane
false

最佳答案

您必须寻找SwingUtilities#getDeepestComponentAt,例如

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

public class TestMouseListener {

    public static void main(String[] args) {
        final JComboBox combo = new JComboBox();
        combo.setEditable(true);
        for (int i = 0; i < 10; i++) {
            combo.addItem(i);
        }
        final JLabel tip = new JLabel();
        tip.setText("Outside combobox");
        JPanel panel = new JPanel();
        panel.add(combo);
        panel.add(tip);
        panel.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseEntered(MouseEvent e) {
                tip.setText("Outside combobox");
            }

            @Override
            public void mouseExited(MouseEvent e) {
                Component c = SwingUtilities.getDeepestComponentAt(
                        e.getComponent(), e.getX(), e.getY());
                tip.setText(c != null && SwingUtilities.isDescendingFrom(
                        c, combo) ? "Inside combo box" : "Outside combobox");
            }
        });
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

    }

    private TestMouseListener() {
    }
}

08-05 01:16