Java Reference
In-Depth Information
Example 14−1: MultiLineLabel.java (continued)
public void setAlignment(Alignment a) { alignment = a; repaint(); }
public void setMarginWidth(int mw) { margin_width = mw; repaint(); }
public void setMarginHeight(int mh) { margin_height = mh; repaint(); }
// Property getter methods. Note that getFont(), getForeground(), etc.
// are inherited from the superclass.
public String getLabel() { return label; }
public Alignment getAlignment() { return alignment; }
public int getMarginWidth() { return margin_width; }
public int getMarginHeight() { return margin_height; }
/**
* This method is called by a layout manager when it wants to
* know how big we'd like to be. In Java 1.1, getPreferredSize() is
* the preferred version of this method. We use this deprecated version
* so that this component can interoperate with 1.0 components.
*/
public Dimension preferredSize() {
if (!measured) measure();
return new Dimension(max_width + 2*margin_width,
num_lines * line_height + 2*margin_height);
}
/**
* This method is called when the layout manager wants to know
* the bare minimum amount of space we need to get by.
* For Java 1.1, we'd use getMinimumSize().
*/
public Dimension minimumSize() { return preferredSize(); }
/**
* This method draws the component.
* Note that it handles the margins and the alignment, but that
* it doesn't have to worry about the color or font--the superclass
* takes care of setting those in the Graphics object we're passed.
**/
public void paint(Graphics g) {
int x, y;
Dimension size = this.size(); // use getSize() in Java 1.1
if (!measured) measure();
y = line_ascent + (size.height - num_lines * line_height)/2;
for(int i = 0; i < num_lines; i++, y += line_height) {
if (alignment == Alignment.LEFT) x = margin_width;
else if (alignment == Alignment.CENTER)
x = (size.width - line_widths[i])/2;
else x = size.width - margin_width - line_widths[i];
g.drawString(lines[i], x, y);
}
}
/**
* This internal method breaks a specified label up into an array of lines.
* It uses the StringTokenizer utility class.
**/
protected synchronized void newLabel() {
StringTokenizer t = new StringTokenizer(label, "\n");
num_lines = t.countTokens();
lines = new String[num_lines];
Search WWH ::




Custom Search