L
Larry Coon
I'm trying to create a JDialog that opens over the center
of its parent JFrame, like the JOptionPane.showXXXDialog
dialogs do. Here's a contrived example to illustrate
the problem. Pushing the "Dialog" button opens a JDialog,
but it always opens at the top-left corner of the screen,
no matter where the parent JFrame is. Is there a way to
change this?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
private JButton dialogButton;
public Test() {
super("This is the JFrame");
dialogButton = new JButton("Dialog");
dialogButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ModalDialog(Test.this);
}
});
getContentPane().add(dialogButton, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 200);
setVisible(true);
}
class ModalDialog extends JDialog {
private JButton closeButton;
public ModalDialog(JFrame parent) {
super(parent, "This is a JDialog", true);
closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
getContentPane().add(closeButton);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
pack();
setVisible(true);
}
}
public static void main(String[] args) {
new Test();
}
}
of its parent JFrame, like the JOptionPane.showXXXDialog
dialogs do. Here's a contrived example to illustrate
the problem. Pushing the "Dialog" button opens a JDialog,
but it always opens at the top-left corner of the screen,
no matter where the parent JFrame is. Is there a way to
change this?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
private JButton dialogButton;
public Test() {
super("This is the JFrame");
dialogButton = new JButton("Dialog");
dialogButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ModalDialog(Test.this);
}
});
getContentPane().add(dialogButton, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 200);
setVisible(true);
}
class ModalDialog extends JDialog {
private JButton closeButton;
public ModalDialog(JFrame parent) {
super(parent, "This is a JDialog", true);
closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
getContentPane().add(closeButton);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
pack();
setVisible(true);
}
}
public static void main(String[] args) {
new Test();
}
}