若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
If you like this post, please click the ads on the blog. Thank you very much.
在用程式語言製作動畫之前,要了解電腦如何產生動畫,可參考此連結:動畫簡介。
Before creating a computer animation with a programming language, the concept:"how a computer produces animations" have to be understood.
If you like this post, please click the ads on the blog. Thank you very much.
Before creating a computer animation with a programming language, the concept:"how a computer produces animations" have to be understood.
那麼要如何在Java裡要產生動畫?利用Timer就可以了。
The Java programming has a Timer class that can generate animations.底下了範例是用Swing Timer來實現將螢幕上的東西從左移動到右。
The following example use Swing Timer to move a square from the left to the right of the screen.
程式碼如下:
The code is:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package holan.tw; | |
import java.awt.Color; | |
import java.awt.Graphics; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import javax.swing.JFrame; | |
import javax.swing.Timer; | |
public class GameAnimation extends JFrame implements ActionListener { | |
final int SCREEN_WIDTH = 400; | |
final int SCREEN_HEIGHT = 400; | |
final int RECT_WIDTH = 20; | |
final int RECT_HEIGHT = 20; | |
final int DELAY_MS = 20; | |
int dx = 1; | |
int xPos = 0; | |
int yPos = SCREEN_HEIGHT / 2; | |
Timer timer; | |
public GameAnimation() { | |
setTitle("遊戲動畫"); | |
setSize(SCREEN_WIDTH, SCREEN_HEIGHT); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setLocationRelativeTo(null); | |
timer = new Timer(DELAY_MS, this); | |
timer.setInitialDelay(190); | |
timer.start(); | |
} | |
public void update(Graphics g) { | |
this.paint(g); | |
} | |
public void paint(Graphics g) { | |
super.paint(g); | |
g.setColor(Color.GREEN); | |
g.fillRect(xPos, yPos, RECT_WIDTH, RECT_HEIGHT); | |
} | |
public static void main(String[] args) { | |
new GameAnimation().show(); | |
} | |
@Override | |
public void actionPerformed(ActionEvent arg0) { | |
this.repaint(); | |
xPos += 1; | |
if( xPos >= SCREEN_WIDTH ) xPos = 0; | |
} | |
} |
沒有留言:
張貼留言