Monday 27 March 2017

Control Fundamentals, Labels & Using Buttons - Java Tutorials

Control Fundamentals

The AWT supports the following types of controls:

  • Labels
  • Push buttons
  • Check boxes
  • Choice lists
  • Lists
  • Scroll bars
  • Text editing

These controls are subclasses of Component.


Adding and Removing Controls

To include a control in a window, you must add it to the window. To do this, you must first create an instance of the desired control and then add it to a window by calling add( ), which is defined by Container. The add( ) method has several forms. The following form is the one that is used for the first part of this chapter:

      Component add(Component compObj)

Here, compObj is an instance of the control that you want to add. A reference to compObj is returned. Once a control has been added, it will automatically be visible whenever its parent window is displayed. Sometimes you will want to remove a control from a window when the control is no longer needed. To do this, call remove( ). This method is also defined by Container. It has this general form:

      void remove(Component obj)

Here, obj is a reference to the control you want to remove. You can remove all controls by calling removeAll( ).


Responding to Controls

Except for labels, which are passive controls, all controls generate events when they are accessed by the user. For example, when the user clicks on a push button, an event is sent that identifies the push button. In general, your program simply implements the appropriate interface and then registers an event listener for each control that you need to monitor. As explained in Chapter 20, once a listener has been installed, events are automatically sent to it. In the sections that follow, the appropriate interface for each control is specified.




Labels

The easiest control to use is a label. A label is an object of type Label, and it contains a string, which it displays. Labels are passive controls that do not support any interaction with the user. Label defines the following constructors:

      Label( )
      Label(String str)
      Label(String str, int how)

The first version creates a blank label. The second version creates a label that contains the string specified by str. This string is left-justified. The third version creates a label that contains the string specified by str using the alignment specified by how. The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.

You can set or change the text in a label by using the setText( ) method. You can obtain the current label by calling getText( ). These methods are shown here:

      void setText(String str)
      String getText( )

For setText( ), str specifies the new label. For getText( ), the current label is returned. You can set the alignment of the string within the label by calling setAlignment( ). To obtain the current alignment, call getAlignment( ). The methods are as follows:

      void setAlignment(int how)
      int getAlignment( )

Here, how must be one of the alignment constants shown earlier. The following example creates three labels and adds them to an applet:

  // Demonstrate Labels
  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="LabelDemo" width=300 height=200>
  </applet>
  */

  public class LabelDemo extends Applet {
    public void init() {
      Label one = new Label("One");
      Label two = new Label("Two");
      Label three = new Label("Three");

      // add labels to applet window
      add(one);
      add(two);
      add(three);
    }
  }

Following is the window created by the LabelDemo applet. Notice that the labels are organized in the window by the default layout manager. Later, you will see how to control more precisely the placement of the labels.




Using Buttons

The most widely used control is the push button. A push button is a component that contains a label and that generates an event when it is pressed. Push buttons are objects of type Button. Button defines these two constructors:

      Button( )
      Button(String str)

The first version creates an empty button. The second creates a button that contains str as a label. After a button has been created, you can set its label by calling setLabel( ). You can retrieve its label by calling getLabel( ). These methods are as follows:

      void setLabel(String str)
      String getLabel( )

Here, str becomes the new label for the button.


Handling Buttons

Each time a button is pressed, an action event is generated. This is sent to any listeners that previously registered an interest in receiving action event notifications from that component. Each listener implements the ActionListener interface. That interface defines the actionPerformed( ) method, which is called when an event occurs. An ActionEvent object is supplied as the argument to this method. It contains both a reference to the button that generated the event and a reference to the string that is the label of the button. Usually, either value may be used to identify the button, as you will see.

Here is an example that creates three buttons labeled “Yes,” “No,” and “Undecided.” Each time one is pressed, a message is displayed that reports which button has been pressed. In this version, the label of the button is used to determine which button has been pressed. The label is obtained by calling the getActionCommand( ) method on the ActionEvent object passed to actionPerformed( ).

  // Demonstrate Buttons
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  /*
    <applet code="ButtonDemo" width=250 height=150>
    </applet>
  */

  public class ButtonDemo extends Applet implements ActionListener {
    String msg = "";
    Button yes, no, maybe;

    public void init() {
      yes = new Button("Yes");
      no = new Button("No");
      maybe = new Button("Undecided");

      add(yes);
      add(no);
      add(maybe);

      yes.addActionListener(this);
      no.addActionListener(this);
      maybe.addActionListener(this);
    }

    public void actionPerformed(ActionEvent ae) {
      String str = ae.getActionCommand();
      if(str.equals("Yes")) {
        msg = "You pressed Yes.";
      }
      else if(str.equals("No")) {
        msg = "You pressed No.";
      }
      else {
        msg = "You pressed Undecided.";
      }
      repaint();
    }

    public void paint(Graphics g) {
      g.drawString(msg, 6, 100);
    }
  }

As mentioned, in addition to comparing button labels, you can also determine which button has been pressed, by comparing the object obtained from the getSource( ) method to the button objects that you added to the window. To do this, you must keep a list of the objects when they are added. The following applet shows this approach:

  // Recognize Button objects.
  import java.awt.*;
  import java.awt.event.*;
  import java.applet.*;
  /*
    <applet code="ButtonList" width=250 height=150>
    </applet>
  */

  public class ButtonList extends Applet implements ActionListener {
    String msg = "";
    Button bList[] = new Button[3];

    public void init() {
      Button yes = new Button("Yes");
      Button no = new Button("No");
      Button maybe = new Button("Undecided");

      // store references to buttons as added
      bList[0] = (Button) add(yes);
      bList[1] = (Button) add(no);
      bList[2] = (Button) add(maybe);

      // register to receive action events
      for(int i = 0; i < 3; i++) {
        bList[i].addActionListener(this);
      }
    }

    public void actionPerformed(ActionEvent ae) {
      for(int i = 0; i < 3; i++) {
        if(ae.getSource() == bList[i]) {
          msg = "You pressed " + bList[i].getLabel();
        }
      }
      repaint();
    }

    public void paint(Graphics g) {
      g.drawString(msg, 6, 100);
    }
  }

In this version, the program stores each button reference in an array when the buttons are added to the applet window. (Recall that the add( ) method returns a reference to the button when it is added.) Inside actionPerformed( ), this array is then used to determine which button has been pressed.

For simple applets, it is usually easier to recognize buttons by their labels. However, in situations in which you will be changing the label inside a button during the execution of your program, or using buttons that have the same label, it may be easier to determine which button has been pushed by using its object reference.

No comments:

Post a Comment