Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
MultiLineLabel.java
1 package ij.gui;
2 import java.awt.*;
3 import java.util.*;
4 
7 public class MultiLineLabel extends Canvas {
8  String[] lines;
9  int num_lines;
10  int margin_width = 6;
11  int margin_height = 6;
12  int line_height;
13  int line_ascent;
14  int[] line_widths;
15  int max_width;
16 
17  // Breaks the specified label up into an array of lines.
18  public MultiLineLabel(String label) {
19  StringTokenizer t = new StringTokenizer(label, "\n");
20  num_lines = t.countTokens();
21  lines = new String[num_lines];
22  line_widths = new int[num_lines];
23  for(int i = 0; i < num_lines; i++) lines[i] = t.nextToken();
24  }
25 
26 
27  // Figures out how wide each line of the label
28  // is, and how wide the widest line is.
29  protected void measure() {
30  FontMetrics fm = this.getFontMetrics(this.getFont());
31  // If we don't have font metrics yet, just return.
32  if (fm == null) return;
33 
34  line_height = fm.getHeight();
35  line_ascent = fm.getAscent();
36  max_width = 0;
37  for(int i = 0; i < num_lines; i++) {
38  line_widths[i] = fm.stringWidth(lines[i]);
39  if (line_widths[i] > max_width) max_width = line_widths[i];
40  }
41  }
42 
43 
44  public void setFont(Font f) {
45  super.setFont(f);
46  measure();
47  repaint();
48  }
49 
50 
51  // This method is invoked after our Canvas is first created
52  // but before it can actually be displayed. After we've
53  // invoked our superclass's addNotify() method, we have font
54  // metrics and can successfully call measure() to figure out
55  // how big the label is.
56  public void addNotify() {
57  super.addNotify();
58  measure();
59  }
60 
61 
62  // Called by a layout manager when it wants to
63  // know how big we'd like to be.
64  public Dimension getPreferredSize() {
65  return new Dimension(max_width + 2*margin_width,
66  num_lines * line_height + 2*margin_height);
67  }
68 
69 
70  // Called when the layout manager wants to know
71  // the bare minimum amount of space we need to get by.
72  public Dimension getMinimumSize() {
73  return new Dimension(max_width, num_lines * line_height);
74  }
75 
76  // Draws the label
77  public void paint(Graphics g) {
78  int x, y;
79  Dimension d = this.getSize();
80  y = line_ascent + (d.height - num_lines * line_height)/2;
81  for(int i = 0; i < num_lines; i++, y += line_height) {
82  x = margin_width;
83  g.drawString(lines[i], x, y);
84  }
85  }
86 
87 }