Bean Introspection  «Prev 

JavaBean's Basic Introspection - Exercise Result

You Said:

Build and test the MyLabel Bean.

Following is the complete Java source code, MyLabel.java, for the MyLabel Bean.
Move your cursor over the boxed lines of code to obtain descriptions of the code content. (A text version follows for those who do not have Java-enabled browsers.)

Apply, Filter, Sort
  1. Java API class imports.
  2. The class definition.
  3. The label property definition.
  4. The default constructor.
  5. The detailed constructor.
  6. The getter method for|the label property.
  7. The setter method for|the label property.
  8. The paint method.


Following is the manifest file, MyLabel.mf, for the MyLabel Bean:

Manifest-Version: 1.0

Name: MyLabel.class Java-Bean: True

Text Version


The complete Java source code, MyLabel.java, for the MyLabel Bean (text version):
1:  // MyLabel Bean Class
2:  // MyLabel.java
3:
4:  // Imports
5:  import java.awt.*;
6:  import java.io.Serializable;
7:
8:  public class MyLabel extends Canvas implements Serializable {
9:    private String label;
10:
11:  // Constructors
12:  public MyLabel() {
13:    this("I'm a label!");
14:  }
15:
16:  public MyLabel(String l) {
17:    // Allow the superclass constructor to do its thing
18:    super();
19:
20:    // Set the label property
21:    label = l;
22:
23:    // Set a default size
24:    setSize(75, 50);
25:  }
26:
27:  // Accessor methods
28:  public String getLabel() {
29:    return label;
30:  }
31:
32:  public void setLabel(String l) {
33:    label = l;
34:  }
35:
36:  // Other public methods
37:  public synchronized void paint(Graphics g) {
38:    int width = getSize().width;
39:    int height = getSize().height;
40:
41:    // Paint the background 
42:    g.setColor(getBackground());
43:    g.fillRect(0, 0, width, height);
44:
45:    // Paint the label (foreground) text
46:    g.setColor(getForeground());
47:    g.setFont(getFont());
48:    FontMetrics fm = g.getFontMetrics();
49:    g.drawString(label, (width - fm.stringWidth(label)) / 2,
50:      (height + fm.getMaxAscent() - fm.getMaxDescent()) / 2);
51:  }
52: }

Lines 5-6:   Java API class imports
Line 8:      The class definition
Line 9:      The label property definition
Lines 12-14: The default constructor
Lines 16-25: The detailed constructor
Lines 28-30: The getter method for the label property
Lines 32-34: The getter method for the label property
Lines 37-51: The paint() method

Namecheap2