Programing

Swing Java에서 JFrame 모달을 만드는 방법

lottogame 2020. 12. 5. 09:10
반응형

Swing Java에서 JFrame 모달을 만드는 방법


JFrame을 사용한 GUI를 하나 만들었습니다. 모달로 만들려면 어떻게해야합니까?


가장 좋은 방법은 창 모달을 만들려면 JFrame 대신 JDialog를 사용하는 것입니다. 자세한 내용은 Java 6의 Modality API 도입에 대한 세부 정보를 확인하십시오 . 튜토리얼있습니다 .

여기에 표시됩니다 몇 가지 예제 코드 JPanel panelA의 JDialog에 모달이다 Frame parentFrame. 생성자를 제외하고는 JFrame.

final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);

편집 : Modality API 링크 업데이트 및 튜토리얼 링크 추가 (범프에 대해 @spork에 끄덕임).


부모에 대한 참조를 전달 JFrame하고 JFrame변수에 보유 하는 클래스를 만들 수 있습니다 . 그런 다음 새 프레임을 만든 프레임을 잠글 수 있습니다.

parentFrame.disable();

//Some actions

parentFrame.enable();

단지 대신 JFrameJDialog클래스

public class MyDialog extends JFrame // delete JFrame and write JDialog

그런 다음 setModal(true);생성자에 작성

그 후 netbeans에서 양식을 구성 할 수 있으며 양식은 모달이됩니다.


  1. 새 JPanel 양식 만들기
  2. 원하는 구성 요소와 코드를 추가하십시오.

YourJPanelForm stuff = new YourJPanelForm();
JOptionPane.showMessageDialog(null,stuff,"Your title here bro",JOptionPane.PLAIN_MESSAGE);


모달 대화 상자가 기다리고 있습니다 ...


내가 아는 한 JFrame은 모달 모드를 수행 할 수 없습니다. 대신 JDialog를 사용하고 호출 setModalityType(Dialog.ModalityType type)하여 모달 (또는 모달 아님)으로 설정하십시오.


JFrame 대신 JDialog를 사용할 준비가 된 경우 ModalityTypeAPPLICATION_MODAL로 설정할 수 있습니다 .

이것은 일반적인 JOptionPane과 동일한 동작을 제공합니다.

import java.awt.event.ActionEvent;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

public class MyDialog extends JFrame {

public MyDialog() {
    setBounds(300, 300, 300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    setLayout(new FlowLayout());
    JButton btn = new JButton("TEST");
    add(btn);
    btn.addActionListener(new ActionListener() 
    {

        @Override
        public void actionPerformed(ActionEvent e) {
            showDialog();
        }
    });
}

private void showDialog() 
{

    JDialog dialog = new JDialog(this, Dialog.ModalityType.APPLICATION_MODAL);
    //OR, you can do the following...
    //JDialog dialog = new JDialog();
    //dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

    dialog.setBounds(350, 350, 200, 200);
    dialog.setVisible(true);
}

public static void main(String[] args) 
{
    new MyDialog();
}
}

이 정적 유틸리티 메서드는 모달 JDialog도 비밀리에 열어 모달 JFrame을 보여줍니다. 여러 데스크톱이있는 Windows 7, 8 및 10에서 성공적으로 올바르게 사용했습니다.

매우 드물게 사용되는 로컬 클래스 기능에 대한 좋은 예입니다 .

import javax.swing.*;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// ... (class declaration)

/**
 * Shows an already existing JFrame as if it were a modal JDialog. JFrames have the upside that they can be
 * maximized.
 * <p>
 * A hidden modal JDialog is "shown" to effect the modality.
 * <p>
 * When the JFrame is closed, this method's listener will pick up on that, close the modal JDialog, and remove the
 * listener.
 *
 * made by dreamspace-president.com
 *
 * @param window the JFrame to be shown
 * @param owner  the owner window (can be null)
 * @throws IllegalArgumentException if argument "window" is null
 */
public static void showModalJFrame(final JFrame window, final Frame owner) {

    if (window == null) {
        throw new IllegalArgumentException();
    }
    window.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
    window.setVisible(true);
    window.setAlwaysOnTop(true);

    final JDialog hiddenDialogForModality = new JDialog(owner, true);
    final class MyWindowCloseListener extends WindowAdapter {
        @Override
        public void windowClosed(final WindowEvent e) {
            window.dispose();
            hiddenDialogForModality.dispose();
        }
    }

    final MyWindowCloseListener myWindowCloseListener = new MyWindowCloseListener();
    window.addWindowListener(myWindowCloseListener);

    final Dimension smallSize = new Dimension(80, 80);
    hiddenDialogForModality.setMinimumSize(smallSize);
    hiddenDialogForModality.setSize(smallSize);
    hiddenDialogForModality.setMaximumSize(smallSize);
    hiddenDialogForModality.setLocation(-smallSize.width * 2, -smallSize.height * 2);
    hiddenDialogForModality.setVisible(true);
    window.removeWindowListener(myWindowCloseListener);
}

도움이 될 수있는 약간의 코드가 있습니다.

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class ModalJFrame extends JFrame {

    Object currentWindow = this;

    public ModalJFrame() 
    {
        super();
        super.setTitle("Main JFrame");
        super.setSize(500, 500);
        super.setResizable(true);
        super.setLocationRelativeTo(null);

        JMenuBar menuBar = new JMenuBar();
        super.setJMenuBar(menuBar);

        JMenu fileMenu = new JMenu("File");
        JMenu editMenu = new JMenu("Edit");

        menuBar.add(fileMenu);
        menuBar.add(editMenu);

        JMenuItem newAction = new JMenuItem("New");
        JMenuItem openAction = new JMenuItem("Open");
        JMenuItem exitAction = new JMenuItem("Exit");
        JMenuItem cutAction = new JMenuItem("Cut");
        JMenuItem copyAction = new JMenuItem("Copy");
        JMenuItem pasteAction= new JMenuItem("Paste");

        fileMenu.add(newAction);
        fileMenu.add(openAction);
        fileMenu.addSeparator();
        fileMenu.add(exitAction);

        editMenu.add(cutAction);
        editMenu.add(copyAction);
        editMenu.addSeparator();
        editMenu.add(pasteAction);

        newAction.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {

                JFrame popupJFrame = new JFrame();

                popupJFrame.addWindowListener(new WindowAdapter()
                {
                      public void windowClosing(WindowEvent e) 
                      {
                          ((Component) currentWindow).setEnabled(true);                     }
                      });

                ((Component) currentWindow).setEnabled(false);
                popupJFrame.setTitle("Pop up JFrame");
                popupJFrame.setSize(400, 500);
                popupJFrame.setAlwaysOnTop(true);
                popupJFrame.setResizable(false);
                popupJFrame.setLocationRelativeTo(getRootPane());
                popupJFrame.setVisible(true);
                popupJFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            }
        });

        exitAction.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                System.exit(0);
            }
        });
    }
    public static void main(String[] args) {

        ModalJFrame myWindow = new ModalJFrame();
        myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myWindow.setVisible(true);
    }
}

이 경우에 내가 한 일은 내가 보이게하려는 기본 jframe (예 : 메뉴 프레임) focusableWindowState에서 속성 창에서 옵션 선택 취소하여 FALSE. 이 작업이 완료되면 내가 호출 한 jframe은 닫을 때까지 초점을 잃지 않습니다.


다른 사람들이 언급했듯이 JDialog를 사용할 수 있습니다. 부모 프레임에 대한 액세스 권한이 없거나 구멍 응용 프로그램을 고정하려는 경우 null을 부모로 전달하면됩니다.

final JDialog frame = new JDialog((JFrame)null, frameTitle, true); frame.setModal(true);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);


JFrame의 내용이 확실하지 않은 경우 사용자에게 입력을 요청하면 JOptionPane을 사용할 수 있으며 JFrame을 모달로 설정할 수도 있습니다.

            JFrame frame = new JFrame();
            String bigList[] = new String[30];

            for (int i = 0; i < bigList.length; i++) {
              bigList[i] = Integer.toString(i);
            }

            JOptionPane.showInputDialog(
                    frame, 
                    "Select a item", 
                    "The List", 
                    JOptionPane.PLAIN_MESSAGE,
                    null,
                    bigList,
                    "none");
            }

The most simple way is to use pack() method before visualizing the JFrame object. here is an example:

myFrame frm = new myFrame();
frm.pack();
frm.setVisible(true);

참고URL : https://stackoverflow.com/questions/1481405/how-to-make-a-jframe-modal-in-swing-java

반응형