![]() |
![]() |
![]() |
![]() |
![]() |
|
Of course, you can substitute any statement you like for the print statement in Segment 885. For example, you can arrange for a thread to increment the position of the text displayed on a component.
Suppose that you decide to define a Marquee class such that
instances can display a message, provided via a constructor, at a position
dictated by the values of the position and drop instance
variables.
The paint method uses the graphics context to display the message in
a large bold font. If the value of the ready variable is
false, then paint first uses the graphics context to
initialize all instance variables, other than message:
import java.awt.*;
import javax.swing.*;
public class Marquee extends JComponent {
private String message;
private int position, drop, initialPosition, delta, messageWidth;
private Font messageFont = new Font("TimesRoman", Font.BOLD, 24);
private boolean ready = false;
public Marquee (String s) {
message = s;
}
public void decrementPosition() {
if (position + messageWidth < 0) {
position = initialPosition;
}
else {
position = position - delta;
}
repaint();
}
public void paint(Graphics g) {
// Determine size:
Dimension d = getSize();
// Set font
g.setFont(messageFont);
if (initialPosition != d.width) {ready = false;}
if (!ready) {
// Set initial position to be the width:
position = initialPosition = d.width;
// Set the font and determine the message width:
FontMetrics f = g.getFontMetrics();
messageWidth = f.stringWidth(message);
// Set delta to be equal to the width of the letter e:
delta = f.stringWidth("e");
// Set drop so as to center the text vertically:
drop = (d.height + f.getHeight() + f.getDescent()) / 2;
ready = true;
}
System.out.println("Painting");
g.drawString(message, position, drop);
}
public Dimension getMinimumSize() {return new Dimension(300, 50);}
public Dimension getPreferredSize() {return new Dimension(300, 50);}
}