在java中我尝试使用容器类中的getComponentAt(x,y)方法。但对于给定的(x,y)坐标,它总是返回类javax.swing.JRootPane的对象,即使(x,y)包含一些图像/ JLabel / JButton。
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
答案 0 :(得分:5)
你必须寻找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() {
}
}
答案 1 :(得分:0)
这取决于您构建UI的方式,但请尝试Container#findCompoinentAt(int x, int y)
- 它会返回最顶层的可见子项。
答案 2 :(得分:0)
问题来自于您将侦听器添加到多个组件这一事实,但您总是引用该帧来检索组件。你应该做的是:
Component c = ((Component)e.getSource()).getComponentAt(e.getX(), e.getY());
// Do some stuff about c.
事件坐标是相对于触发事件的组件。