Friday, 14 February 2014

Java: Add click listener to a Button

Following example adds a listener to the button:

private void addListenerToButton()
{
JButton button = new JButton("OK");
button.addActionListener(new ActionListener()
{

@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("You have clicked OK button");
                                // perform any other operations here
}
});
}

Another example:

private void addListenerToButton()
{
JButton button = new JButton("OK");
button.addActionListener(new OkButtonListener());
}

public class  OkButtonListener implements ActionListener
{
                     
                    @Override
public void actionPerformed(ActionEvent e)
{
System.out.println("You have clicked OK button");
                                // perform any other operations here
}
}

No comments:

Post a Comment