To help you get started coding the
MyLabel Bean,
skeletal helper code is provided, below. Simply provide the missing code wherever you find three astericks (***). If you run into problems, you can always look at my solution to the exercise in the MyLabel.java source code file, which you can obtain by clicking the Resources button to the left. You will also find a manifest file and ready-to-use JAR file for the Bean there.
// MyLabel Bean Class
// MyLabel.java
import java.awt.*;
import java.io.Serializable;
public class MyLabel extends Canvas implements Serializable {
// ----- insert label property declaration code here ***
// Constructors
public MyLabel() {
// insert default constructor code here
}
public MyLabel(String l) {
// insert single-argument constructor code here ***
}
// Accessor methods
public String getLabel() {
// insert getLabel() method code here ***
}
public void setLabel(String l) {
// insert setLabel() method code here ***
}
// Other public methods
public synchronized void paint(Graphics g) {
int width = getSize().width;
int height = getSize().height;
// Paint the background
g.setColor(getBackground());
g.fillRect(0, 0, width, height);
// Paint the label (foreground) text
g.setColor(getForeground());
g.setFont(getFont());
FontMetrics fm = g.getFontMetrics();
g.drawString(label, (width - fm.stringWidth(label)) / 2,
(height + fm.getMaxAscent() - fm.getMaxDescent()) / 2);
}
}