home *** CD-ROM | disk | FTP | other *** search
Java Source | 1996-05-23 | 1.5 KB | 79 lines |
- // MultiLabel.java
- // A multi-line label
- import java.awt.*;
- import java.util.Vector;
-
- public class MultiLabel extends Canvas
- {
- String message;
- FontMetrics fnm = null;
-
- MultiLabel(String msg)
- {
- message = msg;
- }
-
- // paint
- // Render the text into the space available
- public void paint(Graphics g)
- {
- int w = size().width;
- Vector lines = makelines(g, w);
- g.setColor(Color.black);
- for(int y=0; y<lines.size(); y++) {
- // Draw line
- String line = (String)lines.elementAt(y);
- g.drawString(line,
- (w-fnm.stringWidth(line))/2,
- (y+1)*fnm.getHeight());
- }
- }
-
- // makelines
- // Returns a vector of Strings, each less than w pixels
- Vector makelines(Graphics g, int w)
- {
- Vector lines = new Vector();
- if (fnm == null) fnm = g.getFontMetrics();
- String rest = message.trim();
- while(rest.length() != 0) {
- // Get w pixels worth of characters
- int i = rest.length()-1;
- String sub;
- while(fnm.stringWidth(sub = rest.substring(0,i+1)) > w && i > 0)
- i--;
-
- // Break at space if possible
- int spc = sub.lastIndexOf(' ');
- int brk;
- if (spc < 0 || sub.length() == rest.length())
- brk = sub.length(); // cannot or don't need to break
- else
- brk = spc;
-
- // Add line
- lines.addElement(rest.substring(0, brk));
- rest = rest.substring(brk);
- }
- return lines;
- }
-
- public Dimension minimumSize()
- {
- Graphics g = getGraphics();
- if (g == null) {
- return new Dimension(200,120);
- }
- else {
- int lc = makelines(g, 200).size();
- return new Dimension(200, lc*fnm.getHeight());
- }
- }
-
- public Dimension preferredSize()
- {
- return minimumSize();
- }
- }
-
-