Getting the JFrame of a Component

In order to find the frame that contains a component, it is necessary to walk up the component's parents until the frame is encountered. SwingUtilities.getRoot() is a convenience method that finds the frame.

This example implements an action that finds and hides the frame of the component that triggered the action. See also Creating a JButton Component.

// Create an action Action action = new AbstractAction("Action Label") { // This method is called when the action is triggered public void actionPerformed(ActionEvent evt) { Component c = (Component)evt.getSource(); // Get the frame Component frame = SwingUtilities.getRoot(c); // Hide the frame frame.setVisible(false); } };

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.