Generating a mouse event programatically in Swing

In JDK 1.3, you can use the Robot class, very useful for testing purposes. The following example creates a JFrame with a button and left clicks in the center.

Main.java:

import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.awt.*;
  
public class Main extends JFrame
{
   public Main() throws Exception {
      JButton button = new JButton("This button will be clicked");
      getContentPane().add(button);
      pack();
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            System.out.println("Button was clicked!");
         }
      });
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public void generateClickEvent() throws Exception {
      Robot robot = new Robot();
      robot.mouseMove((int) (getSize().getWidth() / 2), (int) (getSize().getHeight() / 2));
      robot.mousePress(InputEvent.BUTTON1_MASK);
      robot.mouseRelease(InputEvent.BUTTON1_MASK);
   }
  
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.show();
      try { Thread.sleep(1000); } catch(InterruptedException e) { } 
      main.generateClickEvent();
   }
}