[英]How to display ImageIcons sequentially each for certain amount of time? Java, Timer
那么假設我有四個ImageIcons,
private ImageIcon characterIntro;
private ImageIcon characterIdle;
private ImageIcon characterAttack;
private ImageIcon characterJump;
Timer time;
它們在構造函數中用gifs初始化。
我知道如何使用我的paintComponent在屏幕上繪制它們,但是如何使它們在一定時間內出現呢? 我想按以下順序進行:
通常我的paintComponent看起來像這樣,並且它同時顯示所有這些:
public void paintComponent (Graphics page)
{
super.paintComponent(page);
page.drawImage(background, 0, 0, null);
if(stage1_completed && stage2_completed && stage3_completed && stage4_completed)
{
characterIntro.paintIcon (this, page, char.x, char.y-10);
characterIdle.paintIcon (this, page, char.x, char.y);
characterAttack.paintIcon (this, page, char.x, char.y);
characterIdle.paintIcon (this, page, char.x, char.y);
characterJump.paintIcon (this, page, char.x, char.y);
characterIdle.paintIcon (this, page, char.x, char.y);
}
}
我如何使用Timer
來達到我想要的效果?
謝謝 :)
對於使用具有不同延遲的Timer
,您可以創建如下方法:
public void scheduleTask(int delay){
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
timer.cancel();
doSomething();
}
} , delay, 1);
}
這將在ms的delay
過去之后運行方法doSomething
。 在doSomething()
方法中,您可以更改應顯示的ImageIcon
,並在下一次delay
再次調用scheduleTask()
方法。
為了實現這一點,我將介紹一個名為Animation
的類,它包含一個圖像以及應該顯示的持續時間。
class Animation{
public ImageIcon Image;
public int Duration;
public Animation(ImageIcon Image, int Duraction){
this.Image = Image;
this.Duration = Duraction;
}
}
使用此類,您可以輕松地創建一系列動畫作為數組。
private Animation[] Sequence = {
new Animation(characterIdle, 3000),
new Animation(characterAttack, 6000),
new Animation(characterIdle, 5000),
new Animation(characterJump, 3000),
new Animation(characterIdle, 3000)
};
我忘記了你的characterIntro圖像。 這將是初始化而不是序列的一部分。
在您的代碼中使用private ImageIcon actualIcon;
保存您要顯示的實際圖像的對象,以及在doSomething()
方法和private int actualSequenceId;
保存序列數組中實際動畫ID的值。
現在,您使用characterIntro
初始化您的actualIcon
對象,並使用scheduleTask(5000);
安排第一次圖像更改scheduleTask(5000);
並實現你的doSomething()
方法,如下所示:
public void doSomething(){
// change the actual Image and schedule next image change
actualImage = Sequence[actualSequenceId].Image;
scheduleTask(Sequence[actualSequenceId].Duration);
// increment sequence Id
if(actualSequenceId + 1 == Sequence.length) actualSequenceId = 0;
else actualSequenceId++;
}
在一個表(或列表)中收集您的圖標
p.ico = new ImageIcon[]{p.characterIntro, p.characterIdle, p.characterAttack, p.characterJump};
然后用“要顯示的內容”邏輯創建一個線程。 像這樣的東西:
new Thread(){
@Override
public void run() {
int[] idxrep = {0,1,2,1,3};
int[] dlyrep = {5,3,6,5,3};
int idx=0;
while (true) {
lbl.setIcon(ico[idxrep[idx]]);
try {Thread.sleep(dlyrep[idx]*1000);}catch(Exception e){}
++idx;
if (idx == idxrep.length) idx=1;//skip intro
}
}
}.start();
lbl
是JLabel
我放入了JPanel
,但你不能以同樣的方式重繪paintComponent()
當前圖標
編輯:
ico
應該在JPanel
中聲明,其中存在所有“字符”。 必須先將字符初始化。 new Thread()
可以放在構造函數中,或者像start()
這樣的專用方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.