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 window = SwingUtilities.getWindowAncestor(popupMenu);

次に、使用して最大化するwindow.setSize()か、それが JFrame であることを知っているように見えるので、それを Frame にキャストしてsetExtendedState、Kevin が言及している方法を使用します。そのための 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.setExtendedState(MAXIMIZED_BOTH) を取得したら、実際に Frame を最大化することについては、おそらく必要なものです。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 に答える