*15.27 (控制一个移动的文本)
请编写一个程序,显示一个移动的文本,如图15-33a和15-33b所示。文本从左到右循环的移动。当它消失在右侧的时候,又会从左侧再次出现。当鼠标按下的时候,文本停滞不动,当按钮释放的时候,将继续移动
习题思路:
- 新建一个直线Line和Text,把直线绑定在面板的中间
- 创建对象PathTransition,路径设置为直线Line,节点设为Text
- 为面板注册一个鼠标事件(鼠标点击:setOnMouseClicked()),左键被点击调用pause()方法,右键点击调用play()方法
代码示例:编程练习题15_27ControlAMovingText.java
package chapter_15;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class 编程练习题15_27ControlAMovingText extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
Pane pane = new Pane();
Scene scene = new Scene(pane, 300, 200);
Line line = new Line(pane.getWidth()*0.2,pane.getHeight()/2.0, pane.getWidth()*1.5, pane.getHeight()/2.0);
Text text = new Text("Programming is fun");
pane.getChildren().add(text);
//pane.getChildren().add(line);//可以显示直线
PathTransition pt = new PathTransition();
pt.setDuration(Duration.millis(2000));
pt.setPath(line);
pt.setNode(text);
pt.setCycleCount(Timeline.INDEFINITE);
pt.play();
pane.setOnMousePressed(e -> pt.pause());
pane.setOnMouseReleased(e -> pt.play());
primaryStage.setTitle("编程练习题14_10DrawCylinder");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
- 结果展示