Animation example in java

JavaFX Animation Tutorial with Examples

In this article, we will have a deep look at JavaFX Animation. JavaFX provides easy to use animation API (javafx.animation package). There are some predefined animation that can be used out of the box or you can implement custom animations using KeyFrames.

Following are the main predefined animations in JavaFX.

1 TranslateTransition

Translate transition allows to create movement animation from one point to another within a duration. Using TranslateTransition#setByX / TranslateTransition#setByY, you can set how much it should move in x and y axis respectively. It also possible to set precise destination by using TranslateTransition#setToX / TranslateTransition#setToY.

import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; import javafx.util.Duration; public class Animation extends Application < @Override public void start(Stage primaryStage) throws Exception < Button btn = new Button("ClickMe"); Group group = new Group(btn); Scene scene = new Scene(group, 600, 600); //Duration = 2.5 seconds Duration duration = Duration.millis(2500); //Create new translate transition TranslateTransition transition = new TranslateTransition(duration, btn); //Move in X axis by +200 transition.setByX(200); //Move in Y axis by +100 transition.setByY(100); //Go back to previous position after 2.5 seconds transition.setAutoReverse(true); //Repeat animation twice transition.setCycleCount(2); transition.play(); primaryStage.setScene(scene); primaryStage.show(); >public static void main(String[] args) < Application.launch(args); >>

2 ScaleTransition

Scale transition is another JavaFX animation which can be used out of the box that allows to animate the scale / zoom of the given object. The object can be enlarged or minimized using this animation.

Читайте также:  Различные элементы массива питон

import javafx.animation.ScaleTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; import javafx.util.Duration; public class Animation extends Application < @Override public void start(Stage primaryStage) throws Exception < Button btn = new Button("Genuine Coder"); Group group = new Group(btn); Scene scene = new Scene(group, 600, 600); //Duration = 2.5 seconds Duration duration = Duration.millis(2500); //Create new scale transition ScaleTransition scaleTransition = new ScaleTransition(duration, btn); //Set how much X should enlarge scaleTransition.setByX(1.5); //Set how much Y should scaleTransition.setByY(1.5); scaleTransition.play(); primaryStage.setScene(scene); primaryStage.show(); >public static void main(String[] args) < Application.launch(args); >>

3 RotateTransition

Rotate transition provides animation for rotating an object. We can provide upto what angle the node should rotate by toAngle. Using byAngle we can specify how much it should rotate from current angle of rotation.

import javafx.animation.RotateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.stage.Stage; import javafx.util.Duration; public class Animation extends Application < @Override public void start(Stage primaryStage) < Button btn = new Button("Genuine Coder"); Group group = new Group(btn); Scene scene = new Scene(group, 600, 600); //Duration = 2.5 seconds Duration duration = Duration.millis(2500); //Create new rotate transition RotateTransition rotateTransition = new RotateTransition(duration, btn); //Rotate by 200 degree rotateTransition.setByAngle(200); rotateTransition.play(); primaryStage.setScene(scene); primaryStage.show(); >public static void main(String[] args) < Application.launch(args); >>

4 FadeTransition

Fade transition creates a fade in / fade out effect by controlling opacity of the object. We can make fade in transition or fade out transition in JavaFX by setting the to and from value.

//Fade in transition FadeTransition fadeInTransition = new FadeTransition(Duration.millis(1500), btn); fadeInTransition.setFromValue(0.0); fadeInTransition.setToValue(1.0); //Fade out transition FadeTransition fadeOutTransition = new FadeTransition(Duration.millis(1500), btn); fadeOutTransition.setFromValue(1.0); fadeOutTransition.setToValue(0.0);

5 PathTransition

Path transition provides option to move object through a specified path. The path can be anything from simple straight line to complex quadratic curves. Following code rotates button through a circular path locate at (200,200) with radius 50

import javafx.animation.PathTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class Animation extends Application < @Override public void start(Stage primaryStage) < Button btn = new Button("Genuine Coder"); Group group = new Group(btn); Scene scene = new Scene(group, 600, 600); //Create new path transition PathTransition pathTransition = new PathTransition(); pathTransition.setDuration(Duration.millis(2500)); //Set node to be animated pathTransition.setNode(btn); //Rotate button through a circular path locate at (200,200) with radius 50 pathTransition.setPath(new Circle(200, 200, 50)); pathTransition.play(); primaryStage.setScene(scene); primaryStage.show(); >public static void main(String[] args) < Application.launch(args); >>

6 Combine Animation Sequentially with SequentialTransition

Sequential transition allows to combine two or more transition we have discussed so far. After the completion of one transition, the next will be started. The following code will apply rotate transition and scale transition sequentially.

//Create rotate transition RotateTransition rotateTransition = new RotateTransition(Duration.seconds(1)); rotateTransition.setByAngle(180f); //Create scale transition ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(1)); scaleTransition.setByX(1.5f); //First do rotateTransition, then do scaleTransition SequentialTransition sequentialTransition = new SequentialTransition(rotateTransition, scaleTransition); sequentialTransition.play();

7 Combine Animation Parallely with ParallelTransition

Parallel transition is very much similar to sequential transition. Except, it works on parallel. All the animations applied will be played in parallel. We can specify two or more transition to execute in parallel.

//Create rotate transition RotateTransition rotateTransition = new RotateTransition(Duration.seconds(1)); rotateTransition.setByAngle(180f); //Create scale transition ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(1)); scaleTransition.setByX(1.5f); //Play both rotateTransition as well as scaleTransition in prallel ParallelTransition sequentialTransition = new ParallelTransition(rotateTransition, scaleTransition); sequentialTransition.play();

8 KeyFrame Animation

KeyFrame animation is one of the most key features of JavaFX Animation. The API javafx.animation.KeyFrame can be used to animate any JavaFX property. For example, let’s say you want to animate width of your application window. You can use widthProperty with KeyFrame to animate the width of your application window.

Watch video on using KeyFrame animation to create slide-in effect in JavaFX.

The following example loads a scene with slide in effect using JavaFX KeyFrame API

Parent root = getNextSceneRoot(); parentContainer.getChildren().add(root); //Create a timeline instance Timeline timeline = new Timeline(); //Create a keyValue. We need to slide in -- We gradually decrement Y value to Zero KeyValue kv = new KeyValue(root.translateYProperty(), 0, Interpolator.EASE_IN); //Create keyframe of 1s with keyvalue kv KeyFrame kf = new KeyFrame(Duration.seconds(1), kv); //Add frame to timeline timeline.getKeyFrames().add(kf); //Start animation timeline.play();

In this chapter we familiarized with JavaFX animation API. JavaFX provides a good set of predefined animation set and a powerful KeyFrame animation API.

You Might also be interested in:-

  • TAGS
  • Animation
  • FadeTransition
  • JavaFX
  • KeyFrame Animation
  • ParallelTransition
  • PathTransition
  • RotateTransition
  • ScaleTransition
  • SequentialTransition
  • TranslateTransition

Источник

Простая анимация на java

сертификат

По сути дела ничего сложного: создаем синий круг, по нажатию кнопки его можно заставить двигаться по диагонали с верхнего левого угла к нижнему правому. В конструкторе класса MovingCircle два параметра — это цвет и скорость (точнее, наоборот, величина замедления). Кроме этого, скорость регулируют еще две строки 57 (x++; — скорость движения по горизонтали) и 58 (y++; — скорость движения по вертикали).

Итак, рисуем кружок зеленого цвета, задаем параметры. В итоге на экране после запуска программы появляется окно с размерами 600 на 550 точек (строка кода 89). В этом окне два поля: рабочая область слева с белым фоном на котором герой нашей статьи — зеленый круг, а справа кнопка: по нажатию кружок начинает двигаться, нажать еще раз — останавливается.

На основе этой простейшей анимации на java можно делать гораздо более сложные. Имеется таймер, все параметры расписаны достаточно подробно: можно, к примеру, использовать квадрат, а не круг. На основе этого примера анимации на java нетрудно уже будет создать самостоятельно анимации других типов. В программе нет комментариев, код должен быть понятен.

А вот и сам код. Можно его скопировать, а можно просто скачать готовый архив с файлом исходника и классами — MovingCircle.zip, либо уже готовый к употреблению архив jar — MovingCircle.jar. Для компилирования и запуска использовалась Java SE Development Kit 7u45 на Windows 7, а также Ubunty 12.04, но должно заработать на любом компьютере, на котором установлена хотя бы jre, хотя бы 2 версии.

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.Timer; @SuppressWarnings("serial") public class MovingCircle extends JComponent implements ActionListener < private double scale; private Color color; private Timer timer; public double x =10; public double y =10; public MovingCircle(Color color, int delay) < scale = 1.0; timer = new Timer(delay, this); this.color = color; setPreferredSize(new Dimension(500, 500)); >public void start() < timer.start(); >public void stop() < timer.stop(); >@Override public void actionPerformed(ActionEvent arg0) < repaint(); >@Override protected void paintComponent(Graphics g) < Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.white); int width = 500; int height = 500; g.fillRect(0, 0, width, height); g2d.setColor(Color.black); g2d.drawRect(0, 0, width - 1, height - 1); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(color); g2d.scale(scale, scale); x++; y++; Ellipse2D el = new Ellipse2D.Double(x, y, 20, 20); g2d.fill(el); >public static void main(String[] args) < SwingUtilities.invokeLater(new Runnable() < public void run() < JFrame frame = new JFrame("Moving Circle"); JPanel panel = new JPanel(); final MovingCircle MovingCircleGreen = new MovingCircle(Color.green, 20); panel.add(MovingCircleGreen); frame.getContentPane().add(panel); final JButton button = new JButton("Start"); button.addActionListener(new ActionListener() < private boolean pulsing = false; @Override public void actionPerformed(ActionEvent e) < if (pulsing) < pulsing = false; MovingCircleGreen.stop(); button.setText("Start"); >else < pulsing = true; MovingCircleGreen.start(); button.setText("Stop"); >> >); panel.add(button); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 550); frame.setVisible(true); > >); > >

Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.

статьи IT, java, анимация

Бесплатный https и
домен RU в подарок

Источник

Create Animation in Java

Create Animation in Java

The JFrame class from the Java Swing library can be used to create different graphics and animations in Java. Until JDK 8 applet was used to create animations, but later it was deleted, and JAVA swing was added.

This tutorial will discuss and demonstrate creating an animation using Java.

Use the JFrame Class to Create Animation in Java

Using JFrame, we can decide colors, shapes, and timings for the animations. Let’s create a 2D rotating pie chart with three parts but six colors.

package delftstack;  import java.awt.Graphics; import java.awt.Color; import java.util.Timer; import java.awt.Insets; import java.util.TimerTask;  import javax.swing.JFrame;  public class Animation extends JFrame    private static int DELAY = 500; //The speed on which the animation will run   Insets animate_insets;   Color colors[] =  Color.PINK, Color.GREEN, Color.ORANGE, Color.BLACK,  Color.WHITE, Color.MAGENTA >;   public void paint(Graphics demo)   super.paint(demo);  if (animate_insets == null)   animate_insets = getInsets();  >  int a = animate_insets.left;  int b = animate_insets.top;  int animation_width = getWidth() - animate_insets.left - animate_insets.right;  int animation_height = getHeight() - animate_insets.top - animate_insets.bottom;  int animation_start = 0;  int animation_steps = colors.length;  int animation_stepSize = 720 / animation_steps;  synchronized (colors)   for (int i = 0; i  animation_steps; i++)   demo.setColor(colors[i]);  demo.fillArc(a, b, animation_width, animation_height, animation_start, animation_stepSize);  animation_start += animation_stepSize;  >  >  >   public void go()   TimerTask animation_task = new TimerTask()   public void run()   Color animation_color = colors[0];  synchronized (colors)   System.arraycopy(colors, 1, colors, 0, colors.length - 1);  colors[colors.length - 1] = animation_color;  >  repaint();  >  >;  Timer animation_timer = new Timer();  animation_timer.schedule(animation_task, 0, DELAY);  >   public static void main(String args[])   Animation Demo_Animation = new Animation();  Demo_Animation.setSize(400, 400);  Demo_Animation.show();  Demo_Animation.go();  > > 

The code above will generate a rotating pie chart with three parts and six different colors.

We can create animations with different shapes and colors using the Java swing library.

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

Источник

Оцените статью