Swing/ScrollingMessage のバックアップの現在との差分(No.2)
TITLE:GlyphVectorで文字列を電光掲示板風にスクロール
GlyphVectorで文字列を電光掲示板風にスクロール
Posted by terai at 2006-11-13- category: swing folder: ScrollingMessage title: GlyphVectorで文字列を電光掲示板風にスクロール tags: [GlyphVector, LineMetrics, TextLayout, Animation, JComponent] author: aterai pubdate: 2006-11-13T04:01:26+09:00 description: GlyphVectorを生成して、これを電光掲示板のようにスクロールさせます。 image:
概要
GlyphVector
を生成して、これを電光掲示板のようにスクロールさせます。
Screenshot
Advertisement
概要
GlyphVectorを生成して、これを電光掲示板のようにスクロールさせます。- &jnlp;
- &jar;
- &zip;
#screenshot
サンプルコード
#spanend
#spandel
class ScrollingMessagePanel extends JComponent implements ActionListener {
#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
#spanadd
class MarqueePanel extends JComponent implements ActionListener {
#spanend
public final javax.swing.Timer animator;
private final GlyphVector gv;
private float xx, yy;
#spandel
#spanend
public ScrollingMessagePanel() {
public MarqueePanel() {
super();
animator = new javax.swing.Timer(10, this);
#spandel
#spanend
String text = "asffdfaaAAASFDsfasdfsdfasdfasd";
Font font = new Font("serif", Font.PLAIN, 100);
FontRenderContext frc = new FontRenderContext(null,true,true);
#spandel
#spanend
Font font = new Font(Font.SERIF, Font.PLAIN, 100);
FontRenderContext frc = new FontRenderContext(null, true, true);
gv = font.createGlyphVector(frc, text);
LineMetrics lm = font.getLineMetrics(text, frc);
yy = lm.getAscent()/2f + (float)gv.getVisualBounds().getY();
yy = lm.getAscent() / 2f + (float) gv.getVisualBounds().getY();
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
#spanadd
#spanend
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int cw = getWidth();
int ch = getHeight();
g2.setPaint(Color.WHITE);
g2.draw(new Line2D.Float(0,ch/2f,cw,ch/2f));
#spandel
#spanend
g2.draw(new Line2D.Float(0, ch / 2f, cw, ch / 2f));
g2.setPaint(Color.BLACK);
g2.drawGlyphVector(gv, cw-xx, ch/2f-yy);
xx = (cw+gv.getVisualBounds().getWidth()-xx > 0) ? xx+2f : 0f;
g2.drawGlyphVector(gv, cw - xx, ch / 2f - yy);
xx = (cw + gv.getVisualBounds().getWidth() - xx > 0) ? xx + 2f : 0f;
}
public void actionPerformed(ActionEvent e) {
#spanadd
#spanend
@Override public void actionPerformed(ActionEvent e) {
repaint();
}
}
解説
上記のサンプルでは、GlyphVectorやLineMetricsから、テキストのVisualBoundsやAscentを取得して、文字列を描画する位置などを計算しています。解説
上記のサンプルでは、GlyphVector
やLineMetrics
からテキストのVisualBounds
やAscent
を取得して文字列を描画する位置などを計算しています。
以下のようにTextLayoutを使用する方法もあります。
- -
- 以下のように
TextLayout
を使用する方法もあるTextLayout tl = new TextLayout(text, font, frc); Rectangle2D b = tl.getBounds(); #spandel yy = tl.getAscent()/2f + (float)b.getY(); #spanend #spanadd yy = tl.getAscent() / 2f + (float) b.getY(); #spanend