1 of 8

Advanced Java Programming

Event Handling

B.Krishnakumar

2 of 8

  • Ex. Buttonwoclick

  • JLabel jlab=new JLabel("click here");
  • jfrm.add(jlab);

  • JButton jbtnAlpha = new JButton("Alpha");
  • Jfrm.add(jbtnAlpha)

  • jfrm.setLayout(new FlowLayout());

3 of 8

  • jbtnAlpha.addActionListener(new ActionListener() {

public void actionPerformed (ActionEvent ae) {

jlab.setText("Alpha was pressed.");

}

});

4 of 8

  • Event handling is a large part of any Swing-based application.
  • The event handling mechanism used by Swing is the same as that used by the AWT. This approach is called the delegation event model.
  • In many cases, Swing uses the same events as does the AWT, and these events are packaged

in java.awt.event. Events specific to Swing are stored in javax.swing.event.

5 of 8

  • program now imports both the java.awt and java.awt.event package
  • java.awt package is needed because it contains the FlowLayout class.
  • java.awt.event package is needed because it defines the ActionListener interface and the ActionEvent class.
  • by default, the content pane uses BorderLayout as its layout manager. However, for this example, FlowLayout is more convenient

6 of 8

  • jfrm.setLayout(new FlowLayout());
  • explicitly call getContentPane( ) to set the layout manager for the content pane.
  • JButton jbtnAlpha = new JButton("Alpha");
  • The msg parameter specifies the string that will be displayed inside the button.
  • When a push button is pressed, it generates an ActionEvent. Thus, JButton provides the addActionListener( ) method, which is used to add an action listener

7 of 8

  • void actionPerformed(ActionEvent ae)
  • This method is called when a button is pressed.

jbtnAlpha.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

jlab.setText("Alpha was pressed.");

}

});

8 of 8

  • jfrm.add(jbtnAlpha);
  • jlab is added to the content pane and window is made visible
  • Remember that all event handlers, such as actionPerformed( ), are called on the event dispatching thread. Therefore, an event handler must return quickly in order to avoid slowing down the application. If your application needs to do something time consuming as the result of an event, it must use a separate thread.