tags:

views:

315

answers:

3

I am trying to maximize JFrame from within JMenuBar, I can not pass a reference to the frame. Is it possible to get a reference to the frame that it is used in?

i can get to the top level component but it does not have a way to maximize and minimize frame.

    public Container getApplicationFrame(ActionEvent event){
         JMenuItem menuItem = (JMenuItem) event.getSource();  
         JPopupMenu popupMenu = (JPopupMenu) menuItem.getParent();  
         Component invoker = popupMenu.getInvoker(); 
         JComponent invokerAsJComponent = (JComponent) invoker;  
         Container topLevel = invokerAsJComponent.getTopLevelAncestor();  
         return topLevel;
    }
A: 

Surely you can stash the frame in question in a local variable somewhere?

As for actually maximizing the Frame once you've got ahold of it, Frame.setExtendedState(MAXIMIZED_BOTH) is probably what you want. Javadoc

While not as elegant as it could be, quick path to ground on your existing code:

public Frame getApplicationFrame(ActionEvent event){
         if(event.getSource() == null) return null;

         Window topLevel = SwingUtilities.getWindowAncestor(event.getSource());

         if(!(topLevel instanceof Frame)) return null;

         return (Frame)topLevel;
}

...
//Somewhere in your code
Frame appFrame = getApplicationFrame(myEvent);
appFrame.setExtendedState(appFrame.getExtendedState() | Frame.MAXIMIZED_BOTH);
...

Minimum Java version 1.4.2. Be forwarned I have not tested the above code, but you should get the idea.

Kevin Montrose
A: 

The class that creates the frame and the menubar can also act as the ActionListener for the menu item, since it has access both the frame and the menubar.

ammoQ
+4  A: 

You can get the Window that contains the JPanel via

Window window = SwingUtilities.getWindowAncestor(popupMenu);

You can then either maximise it using window.setSize() -- or, since you seem to know that it's a JFrame, cast it to Frame and use the setExtendedState method that Kevin mentions. Example code from the Java Developers' Almanac for that:

// This method minimizes a frame; the iconified bit is not affected
public void maximize(Frame frame) {
    int state = frame.getExtendedState();

    // Set the maximized bits
    state |= Frame.MAXIMIZED_BOTH;

    // Maximize the frame
    frame.setExtendedState(state);
}
schweerelos