Let's repeat our AWT example written for Swing.
File: "swing1.java"
import java.awt.*;
import java.awt.event.*;
import javax.swing.* ;
public class swing1 extends JFrame implements ActionListener
{
swing1()
{
JButton buttonObj = new JButton("Click me");
buttonObj.setBounds(30,100,100,30);// setting button position
add(buttonObj);//adding button into frame
buttonObj.addActionListener( this ) ;
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public void actionPerformed(ActionEvent event)
{
//code that reacts to the action...
System.out.println( "Button clicked." ) ;
}
public static void main(String args[])
{
swing1 frameObj =new swing1();
}
}
Output:
If we look at the code carefully we see that it is very similar to the AWT example. In fact the "ActionListener" is from the same package .