▷JDialog는 JFrame과 마찬가지로 우측 상단에 종료 버튼 [×]를 제공, 기본 기능은 JDialog를 화면에서 숨김
▷JDialog를 완전히 제거하고 싶다면 setDefaultCloseOperation(JDialog. DISPOSE_ON_CLOSE)를 호출
◎ 종료 버튼에 적용할 수 있는 기능
NO
기능별 상수
설명
1
WindowConstants.DO_NOTHING_ON_CLOSE
아무 것도 하지 않음
2
WindowConstants.HIDE_ON_CLOSE
화면에서 JDialog 숨김(기본)
3
WindowConstants.DISPOSE_ON_CLOSE
화면에서 JDialog 완전히 제거
int left = owner.getLocationOnScreen().x + (owner.getWidth()-dialog.getWidth())/2; int top = owner.getLocationOnScreen().y + (owner.getHeight()-dialog.getHeight())/2;
◎ 다이얼로그 띄우기 클릭시 모달 다이어로그 나타남 예([닫기] 클릭시 사라지게 함)
1. JDialogExample 다이얼로그
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class JDialogExample extends JDialog {
private JButton btnClose;
// 다이얼로그 설정
public JDialogExample(JFrame owner) {
super(owner);
this.setTitle("JDialogExample");
this.setSize(300, 200);
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setResizable(false);
this.setModal(true);
this.setLocation(
owner.getLocationOnScreen().x + (owner.getWidth() - this.getWidth())/2,
owner.getLocationOnScreen().y + (owner.getHeight() - this.getHeight())/2
);
this.getContentPane().add(getBtnClose(), BorderLayout.SOUTH);
}
// 남쪽 버튼 생성
public JButton getBtnClose() {
if(btnClose == null) {
btnClose = new JButton();
btnClose.setText("닫기");
btnClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JDialogExample.this.dispose();
}
});
}
return btnClose;
}
}
2. JFrameExample 프레임
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class JFrameExample extends JFrame {
private JButton btnOpenDialog;
// 메인 윈도우 설정
public JFrameExample() {
this.setTitle("JFrame");
this.setSize(500, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(getBtnOpenDialog(), BorderLayout.SOUTH);
}
// 남쪽 버튼 생성
public JButton getBtnOpenDialog() {
if(btnOpenDialog == null) {
btnOpenDialog = new JButton();
btnOpenDialog.setText("다이얼로그 띄우기");
btnOpenDialog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
// 다이얼로그 띄우기
JDialogExample jDialog = new JDialogExample(JFrameExample.this);
jDialog.setVisible(true);
}
});
}
return btnOpenDialog;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrameExample jFrame = new JFrameExample();
jFrame.setVisible(true);
}
});
}
}
다이얼로그 창을 띄우면 프레임 창은 선택할 수 없게됩니다.
JDialog를 이용하면 새로운 창을 생성할 수 있습니다. 대신 호출했던 부모창은 비활성화되어서 다이얼로그 창을 닫아야만 부모창을 선택할 수 있게됩니다.
다이얼로그는 새로운 창을 이용할 수 있지만 부모창을 사용할 수 없다는 것을 고려해야겠네요!