Java modal window with maximize button

后端 未结 3 2031
灰色年华
灰色年华 2021-01-02 06:26

How could I create a window which is modal and has a maximize button?
So is it possible to create a modal JFrame or create a JDialog with maxim

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 06:34

    Here is an alternate / slightly more detailed answer.

    Try Are You Missing Maximize Button? (formerly here). This is a github archive of blog articles and code by Santhosh Kumar Tekturi from the now defunct JRoller site.

    It is a complete utility class that makes a Frame mimic a Dialog, similar to the other answers. It involves adding a WindowListener to the Frame to keep the frame on top of its owner and keep its owner frame disabled (warning: in the windowClosed method it should probably be frame.removeWindowListener(this);, and a WindowListener to the owner to keep the frame on top of it and to remove the listener. It also uses its own EventQueue to process events. Note this is an old post, so as mentioned in the code there may be newer APIs to deal with this code better.

    Here is the core function. See the link for the rest. Note: the code in the repository differs from the article; I believe the repository is more developed.

    // show the given frame as modal to the specified owner.
    // NOTE: this method returns only after the modal frame is closed.
    public static void showAsModal(final Frame frame, final Frame owner){
        frame.addWindowListener(new WindowAdapter(){
            public void windowOpened(WindowEvent e){
                owner.setEnabled(false);
            }
    
            public void windowClosing(WindowEvent e) {
                owner.setEnabled(true);
            }
    
            public void windowClosed(WindowEvent e){
                frame.removeWindowListener(this); // originally called on owner
            }
        });
    
        owner.addWindowListener(new WindowAdapter(){
            public void windowActivated(WindowEvent e){
                if(frame.isShowing()){
                    frame.setExtendedState(JFrame.NORMAL);
                    frame.toFront();
                }else
                    owner.removeWindowListener(this);
            }
        });
    
        owner.toFront();
        frame.setVisible(true);
        try{
            new EventPump(frame).start();
        } catch(Throwable throwable){
            throw new RuntimeException(throwable);
        }
    }
    

提交回复
热议问题