"Is there any way that I can change this so that the dialog appears at the middle and of acceptable size?"
If you just add components to it, pack it, and set it location relative to null, it should work fine
It is preferred to .pack()
instead of setting a size. For pack to work, you need to actually add components. the .pack()
will do exactly as it's name suggest - pack the frame with respecting all the added components' preferred sizes.
Also with setLocationRelativeTo()
you set the dialog loation relative to a component. If you use null
, it will be centered on the screen always. But if you set the location relative to its parent, the frame, it will appear centered over the frame.
I have absolutely no idea what you're trying to achieve with the timer, so I just prefer to no-comment
See example
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.Timer;
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame();
final MyDialog dialog = new MyDialog(f, "Title", true);
Timer timer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();
dialog.setVisible(true);
System.out.println("Dialog closed");
}
private static class MyDialog extends JDialog {
public MyDialog(JFrame frame, String title, boolean modal) {
super(frame, title, modal);
setLayout(new BorderLayout());
add(new JButton("NORTH"), BorderLayout.NORTH);
add(new JButton("SOUTH"), BorderLayout.SOUTH);
add(new JButton("EAST"), BorderLayout.EAST);
add(new JButton("WEST"), BorderLayout.WEST);
add(new JButton("CENTER"), BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
}
}
As a side note, you should be running Swing apps from the Event Dispatch Thread (EDT) like this
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
// the code from your main method here
}
});
}