2009-05-12 11 views
1

JMenuBarからJFrameを最大化しようとしていますが、フレームへの参照を渡すことができません。それが使用されているフレームへの参照を取得することは可能ですか?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; 
    } 

答えて

5

あなたはその後、window.setSize()を使用して、それを最大限に高めることができますいずれか

Window window = SwingUtilities.getWindowAncestor(popupMenu); 

経由のJPanelが含まれているウィンドウを取得することができます - または、あなたはそれはJFrameのだということを知っているように見えることから、フレームを使用して、それをキャストsetExtendedState Kevinが言及する方法。そのためには、Java Developers 'AlmanacのExample code

// 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); 
} 
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を。私は上記のコードをテストしていませんが、あなたは考えを得るべきです。

0

フレームとメニューバーを作成するクラスは、フレームとメニューバーの両方にアクセスできるため、メニュー項目のActionListenerとしても機能します。

関連する問題