题
我正在尝试从Jmenubar内部最大化Jframe,我无法将其引用。是否可以参考使用它的框架?
我可以到达顶级组件,但是它没有办法最大化和最小化框架。
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;
}
解决方案
您可以获取包含jpanel的窗口
Window window = SwingUtilities.getWindowAncestor(popupMenu);
然后,您可以使用 window.setSize()
- 或者,既然您似乎知道这是一个Jframe,请施放并使用 setExtendedState
凯文提到的方法。 示例代码 从Java开发人员的年鉴到
// 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);
}
其他提示
当然,您可以将有关框架存放在某个地方的本地变量中?
至于实际上最大化框架后,您可能想要的是frame.setextendedstate(maximized_both)。 Javadoc
虽然不像可能的那样优雅,但快速迈向现有代码:
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);
...
最小Java版本1.4.2。被认为我尚未测试上述代码,但是您应该明白这个想法。
创建框架和Menubar的课程也可以充当菜单项的ActionListener,因为它可以访问框架和Menubar。
不隶属于 StackOverflow