【问题标题】:Controlling JFrame from JMenuBar从 JMenuBar 控制 JFrame
【发布时间】:2009-05-12 04:10:59
【问题描述】:

我正在尝试从 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;
    }

【问题讨论】:

    标签: java swing jframe


    【解决方案1】:

    您可以通过

    获取包含JPanel的Window
    Window window = SwingUtilities.getWindowAncestor(popupMenu);
    

    然后您可以使用window.setSize() 最大化它——或者,因为您似乎知道它是一个JFrame,所以将它转换为Frame 并使用Kevin 提到的setExtendedState 方法。 Example code 来自 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);
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-15
          • 1970-01-01
          相关资源
          最近更新 更多