1

我试图从 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;
    }
4

3 回答 3

5

您可以通过以下方式获取包含 JPanel 的窗口

Window window = SwingUtilities.getWindowAncestor(popupMenu);

然后,您可以使用window.setSize()-- 最大化它,或者,因为您似乎知道它是一个 JFrame,所以将它转换为 Frame 并使用setExtendedStateKevin 提到的方法。Java Developers' Almanac 中的示例代码

// 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);
}
于 2009-05-12T04:34:54.933 回答
1

当然,您可以将有问题的框架存放在某个局部变量中吗?

至于实际最大化 Frame 一旦你掌握了它, 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。请注意,我没有测试过上面的代码,但你应该明白了。

于 2009-05-12T04:21:15.113 回答
0

创建框架和菜单栏的类也可以充当菜单项的 ActionListener,因为它可以访问框架和菜单栏。

于 2009-05-12T04:28:27.550 回答