Wednesday 27 February 2013

29. What will be printed to the standard output when the following program

29. What will be printed to the standard output when the following program
is run and the Test button is pressed 3 times.



Choices:
a. Clicked
Clicked again
Clicked
Clicked again
Clicked
Clicked again
b. Clicked
Clicked
Clicked
c. Clicked
Clicked
Clicked again
Clicked
Clicked again
Clicked again
d. Clicked
Clicked again


Answer:-

C is the correct choice. When the button is clicked for the first time, the actionPerformed method is invoked and it prints "Clicked". In actionPerformed, one more listener is registered with the button. So when the button is clicked for the second time, the actionPerformed of both the listeners is invoked. So it prints "Clicked" and then "Clicked again". Now one more listener is registered with the button. So for the third time the button is clicked, 3 actionPerformed methods are invoked - result is the printing of "Clicked" by first listener,"Clicked again" by the second and "Clicked again" by the third one. Thus C is the correct choice.
==
import java.awt.*;
import java.awt.event.*;

public class ActionTest extends Frame
{
                 public ActionTest()
  {
  Button test=new Button("Test");
  add(test);
  test.addActionListener(new ActionListener()
  {
  public void actionPerformed(ActionEvent e)
  {
  System.out.println("Clicked");
  Button b=(Button)e.getSource();
  b.addActionListener(new ActionListener()
  {
  public void actionPerformed(ActionEvent e)
  {
  System.out.println("Clicked again");
  }
  });
  }
  });

                                setSize(100,100);
    setVisible(true);
                                setTitle("My Frame");
      }

  public static void main(String rgs[])
  {
                              new ActionTest();
  }
}

No comments:

Post a Comment