Java Swing How to - Create getComponentAt() to get Component from JFrame








Question

We would like to know how to create getComponentAt() to get Component from JFrame.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
//from  ww w  . ja v a 2s  . com
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.pack();

    Container contentPane = frame.getContentPane();
    contentPane.setLayout(null);
    for (int i = 0; i < 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 static Component getComponentAt(Container parent, Point p) {
    Component comp = null;
    for (Component child : parent.getComponents()) {
      if (child.getBounds().contains(p)) {
        comp = child;
      }
    }
    return comp;
  }
}