SE450: Example Applet [8/63] Previous pageContentsNext page

file:horstmann/ch08_applet/BannerApplet.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package horstmann.ch08_applet;
import java.applet.Applet;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;

import javax.swing.Timer;

@SuppressWarnings("serial")
public class BannerApplet extends Applet
{
  public void init()
  {
    message = getParameter("message");
    String fontname = getParameter("fontname");
    int fontsize = Integer.parseInt(getParameter("fontsize"));
    delay = Integer.parseInt(getParameter("delay"));
    font = new Font(fontname, Font.PLAIN, fontsize);
    Graphics2D g2 = (Graphics2D) getGraphics();
    FontRenderContext context = g2.getFontRenderContext();
    bounds = font.getStringBounds(message, context);

    timer = new Timer(delay, event -> {
      start--;
      if (start + bounds.getWidth() < 0)
        start = getWidth();
      repaint();
    });
  }

  public void start()
  {
    timer.start();
  }

  public void stop()
  {
    timer.stop();
  }

  public void paint(Graphics g)
  {
    g.setFont(font);
    g.drawString(message, start, (int) -bounds.getY());
  }

  private Timer timer;
  private int start;
  private int delay;
  private String message;
  private Font font;
  private Rectangle2D bounds;
}

Previous pageContentsNext page