JFrame control from JMenuBar
I am trying to maximize a JFrame from a JMenuBar, I cannot pass a link to the frame. Can I get a link to the frame in which it is used?
I can get the top-level component, but it has no way to maximize and minimize the 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 source to share
You can get the window containing the JPanel via
Window window = SwingUtilities.getWindowAncestor(popupMenu);
Then you can maximize it with window.setSize()
- or, since you seem to know it is a JFrame, cast it to Frame and use the method setExtendedState
Kevin mentions. Sample code from the Java Developers Almanac to do this:
// 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);
}
a source to share
Surely you can query the corresponding frame in a local variable?
As for actually maximizing the frame, once you get it, Frame.setExtendedState (MAXIMIZED_BOTH) is probably what you want. Javadoc
While not as nifty as it can be, a quick way to land in 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);
...
The minimum Java version is 1.4.2. Be warned I haven't tested the above code, but you should get the idea.
a source to share