繁体   English   中英

从JMenuBar控制JFrame

[英]Controlling JFrame from JMenuBar

我正在尝试从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,所以将其转换为Frame并使用Kevin提到的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)可能就是您想要的。 Java文档

虽然不尽如人意,但可以快速了解现有代码:

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。 警告我还没有测试上面的代码,但是您应该明白这一点。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM