Center a JFrame on the screen

Use this little code snippet:

   Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
   int x = (int) ((d.getWidth() - getWidth()) / 2);
   int y = (int) ((d.getHeight() - getHeight()) / 2);
   setLocation(x, y);

Applied:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame
{ 
   public Main() {
      final JButton button = new JButton("Center me!");
      getContentPane().setLayout(new FlowLayout());
      getContentPane().add(button);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            int x = (int) ((d.getWidth() - getWidth()) / 2);
            int y = (int) ((d.getHeight() - getHeight()) / 2);
            setLocation(x, y);
         }
      });
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
   
      setSize(new Dimension(200, 200));
   } 
 
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}