以下はjavafx scriptでテキストスクロールを実装している。javafx 2.0で使えるように実現してみた。なお、javafx 2.xではjavafx scriptは廃止される意向(Oracle)
Swing UIよりvisualなことが実現できるし、Java 8だとJavaFXが標準UIになることから、SwingUIを使っている場合はJavaFXにマイグレーションするのがよさそう。
JavaFx Animations – Auto text scrolling using Timeline and KeyFrame
public class TextScroll extends VBox
{
private Number x;
private Number y;
private double width;
private double height;
private Paint stroke;
private Number strokeWidth;
private Text scrollingText;
public TextScroll()
{
Group root = new Group();
String scroll_char = "ここにスクロールする文字を入れる";
scrollingText = TextBuilder.create()
.text(scroll_char)
.layoutX(50)
.textOrigin(VPos.TOP)
.textAlignment(TextAlignment.JUSTIFY)
.fill(Color.PINK)
.font(Font.font("SansSerif", FontPosture.ITALIC, 25))
.build();
Group myGroup = GroupBuilder.create()
.children(scrollingText)
.clip(RectangleBuilder.create()
.width(1000)
.height(40)
.build()
)
.build();
width = scroll_char.length()* 20;
root.getChildren().add(myGroup);
this.getChildren().add(root);
scrollUp();
}
public boolean isScrollingText ()
{
return true;
}
public void scrollUp ()
{
autoTimer.play();
}
public void stopScrolling ()
{
autoTimer.stop ();
}
@SuppressWarnings("unchecked")
private Timeline autoTimer = TimelineBuilder.create()
.cycleCount(Timeline.INDEFINITE)
.keyFrames(new KeyFrame(
new Duration(10L),
new EventHandler(){
public void handle(Event arg0) {
if (scrollingText.getTranslateX() + width < 0)
{
scrollingText.setTranslateX(0.0);
}
// scrollingText.setTranslateY(scrollingText.getTranslateX()-0.5);
scrollingText.setTranslateX(scrollingText.getTranslateX()-0.5);
}
}
)).build();
}