The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing  [141 examples] > JFrame, JWindow, JDialog  [6 examples]

e738. 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 e743 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);
        }
    };

 Related Examples
e733. Creating a JFrame
e734. Exiting an Application When a JFrame Is Closed
e735. Disabling the Close Button on a JFrame
e736. Creating a Borderless Window
e737. Showing a Dialog Box

See also: Actions    JButton    JCheckBox    JComboBox    JDesktop and JInternalFrame    JLabel    JList    JProgressBar    JRadioButton    JScrollPane    JSlider    JSpinner    JSplitPane    JTabbedPane    JToolBar    Keystrokes and Input Maps    Layout    Look and Feel    Menus    Progress Monitor    The Screen    Tool Tips    UI Default Values   


© 2002 Addison-Wesley.