Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are lots of problems with using <code>getComponentAt</code></p> <p>The first is, the parent container must actually be realized and sized. If not, it will return <code>null</code>. The method is capable of returning the container itself if no children exist at the location.</p> <p>I then child <code>Component#contains</code> to test to see if the given point feel within the child components directly, but this wants the point to be translated into the child's coordinate space...</p> <p>So instead, I simply went straight to <code>getBounds</code>...</p> <pre><code>import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.EventQueue; import java.awt.Point; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class TestComponentLocation { public static void main(String[] args) { new TestComponentLocation(); } public TestComponentLocation() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.pack(); frame.setLocationRelativeTo(null); Container contentPane = frame.getContentPane(); contentPane.setLayout(null); for (int i = 0; i &lt; 4; i++) { JPanel panel = new JPanel(); panel.setBounds((i * 75) + 475, 25, 75, 100); System.out.println(panel.getBounds()); contentPane.add(panel); panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3)); } System.out.println(getComponentAt(contentPane, new Point(475, 25))); System.out.println(getComponentAt(contentPane, new Point(100, 25))); frame.setVisible(true); } }); } public Component getComponentAt(Container parent, Point p) { Component comp = null; for (Component child : parent.getComponents()) { if (child.getBounds().contains(p)) { comp = child; } } return comp; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload