概述Swing中的Timer對象
最近在學(xué)習(xí)Swing中的動畫繪制,用到了Timer 這個類,于是寫一點筆記,和大家分享。大家有什么好的例子不妨共享出來吧??!
Timer在java.swing包中的Timer對象來創(chuàng)建,它可以看做是GUI的一個組件。與其他組件不一樣的是,它沒有可以顯示在屏幕上的直觀的外觀。正如名字所表達的,它只幫我們來計時。
Timer對象按相等的時間間隔來產(chǎn)生動作事件。執(zhí)行動畫程序時,可以設(shè)置Timer來定期產(chǎn)生動作事件,然后在動作監(jiān)聽器中更新動畫圖形。
下面來點實際的例子,例子要完成的是:一張圖片在窗口內(nèi)按一定的角度滑行,碰到窗口的邊界時在彈回來。
- importjava.awt.Color;
- importjava.awt.Dimension;
- importjava.awt.Graphics;
- importjava.awt.event.ActionEvent;
- importjava.awt.event.ActionListener;
- importjavax.swing.ImageIcon;
- importjavax.swing.JFrame;
- importjavax.swing.JPanel;
- importjavax.swing.Timer;
- /**
- *演示如何使用Timer這個類來完成Swing的動畫效果。
- *@authorguanminglin<guanminglin@gmail.com>
- */
- publicclassReboundPanelextendsJPanel{
- privatefinalintpanelWidth=300,panelHeight=200;
- privatefinalintDELAY=20,IMAGE_SIZE=35;
- privateImageIconimage;
- privateTimertimer;
- privateintx,y,moveX,moveY;
- /**
- *面板構(gòu)造函數(shù),初始化面板。包括Timer的場景。
- */
- publicReboundPanel(){
- timer=newTimer(DELAY,newReboundListener());
- image=newImageIcon("images/1.gif");
- x=0;
- y=40;
- moveX=moveY=3;
- setPreferredSize(newDimension(panelWidth,panelHeight));
- setBackground(Color.BLACK);
- timer.start();
- }
- /**
- *繪出圖像在面板中的位置。
- *@parampage
- */
- @Override
- publicvoidpaintComponent(Graphicspage){
- super.paintComponent(page);
- image.paintIcon(this,page,x,y);
- }
- //Swing動畫,不斷的更新圖像的位置,已達到動畫的效果。
- privateclassReboundListenerimplementsActionListener{
- publicvoidactionPerformed(ActionEvente){
- x+=moveX;
- y+=moveY;
- if(x<=0||x>=panelWidth-IMAGE_SIZE){
- moveXmoveX=moveX*(-1);
- }
- if(y<=0||y>=panelHeight-IMAGE_SIZE){
- moveYmoveY=moveY*(-1);
- }
- repaint();
- }
- }
- publicstaticvoidmain(String[]args){
- JFrameframe=newJFrame("Rebound");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.add(newReboundPanel());
- frame.pack();
- frame.setVisible(true);
- }
- }
在程序中,類ReboundPanel 類的構(gòu)造方法創(chuàng)建了一個Timer對象,Timer構(gòu)造方法的第一個參數(shù)是延遲時間(也就是間隔時間),第二個參數(shù)是要處理Timer動作事件的監(jiān)聽器。構(gòu)造方法中還設(shè)置了圖像的初始位置,及每次移動是垂直和水平方向的像素變化量。
監(jiān)聽器的actionPerformed()方法更新當前的x和y坐標,然后檢查它是否會令圖像撞到面板的邊界。如果撞上,則調(diào)整運動方向,讓圖像按與原水平、垂直或者兩者的反方向運動。更新坐標值后,actionPerformed() 方法調(diào)用repaint方法重繪組件。調(diào)用repaint方法最終又會調(diào)用paintComponent方法,它在新的位置重繪圖像。
最終效果如下:
【編輯推薦】