Flash中的逐幀動畫可以實現文本移動顯示的效果,java程序也可以實現類似效果哦。
1.Ticker類繼承Canvas,實現Runnable接口。用Canvas中的paint方法控制字符串的移動位置。
2.TickerFrame 類繼承Frame,實現ActionListener窗口,添加兩個按鈕來控制文本的移動和停止。
核心部分:
字符串快要離開顯示區域是,需要復位減少的x坐標值。由于那時的x坐標值和文本寬度相等,這就意味著需要確定字符串的寬度。而字符串寬度依賴于選定的字體、字號和外觀。這里使用了FontMetrics類,用它能獲得關于特定字體信息、度量一個字符串在特定字體情況下的尺寸。但此類是抽象類,不能被實例化,所以還應該使用一個getFontMetrics方法來獲得FontMetrics對象的引用。
代碼如下:
1 import java.awt.*; 2 import java.awt.event.*; 3 class Ticker extends Canvas implements Runnable 4 { 5 //定義字符串位置坐標 6 PRivate int x,y; 7 //定義整型變量用來存儲字符串的高度,寬度 8 private int height,width; 9 private Thread runner=null; 10 //定義字符串 11 private String text=null; 12 //FontMetrics類可以測出具有特定字體的字符大小,但是是抽象類,不能直接被實例化, 13 14 private FontMetrics metrics =null; 15 private Font font=new Font("Monospaced",Font.BOLD,50); 16 17 public Ticker(String _text) 18 { 19 text=_text; 20 //使用getFontMetrics方法,返回一個FontMetrics對象的引用 21 metrics=getFontMetrics(font); 22 //高度等于這種字體的高度 23 height=metrics.getHeight(); 24 //寬度等于字符串的寬 25 width=metrics.stringWidth(text); 26 27 x=getSize().width; 28 y=height; 29 30 //Ticker的尺寸至少應該和文本一般大 31 setSize(width,height+2); 32 33 } 34 //自定義線程啟動的方法 35 public void start() 36 { 37 if(runner==null) 38 { 39 runner=new Thread(this); 40 runner.start(); 41 } 42 } 43 //自定義停止線程的方法 44 public void stop() 45 {runner=null;} 46 47 //實現run方法 48 public void run() 49 { 50 Thread currentThread =Thread.currentThread(); 51 while(runner==currentThread) 52 { 53 //自定義方法,使字符串向左移動坐標改變 54 computeCoordinates(); 55 //重繪 56 repaint(); 57 try 58 { 59 runner.sleep(30); 60 } 61 catch (InterruptedException ie) 62 { 63 System.err.println("Error:"+ie); 64 } 65 } 66 } 67 //重寫父類的paint()方法 68 public void paint(Graphics g) 69 { 70 g.setColor(Color.blue); 71 g.setFont(font); 72 g.drawString(text,x,y); 73 } 74 75 private void computeCoordinates() 76 { 77 //當所有文本移到窗口外時,復位 78 if(x<-width) 79 x=getSize().width; 80 else 81 //坐標減小,已達到字符串向左移動的效果 82 x-=2; 83 84 } 85 86 } 87 public class TickerFrame extends Frame implements ActionListener 88 {
//定義兩個按鈕 89 private Button start=new Button("Start"); 90 private Button stop=new Button("Stop");
//創建Ticker類對象 91 Ticker ticker=new Ticker("實踐中學習!");
//在構造方法中初始化窗口 92 public TickerFrame() 93 { 94 super("移動的文本"); 95 setLayout(new BorderLayout()); 96 add("Center",ticker);
//新建一個容器 97 Panel p=new Panel();
//設置為流式布局 98 p.setLayout(new FlowLayout());
//把按鈕添加到容器中,并為按鈕注冊監聽器 99 p.add(start); start.addActionListener(this);100 p.add(stop); stop.addActionListener(this);101 add("South",p);
//用匿名內部類,為窗口注冊監聽器。102 addWindowListener(new WindowAdapter()103 {104 public void windowClosing(WindowEvent we)105 {106 System.exit(0);107 }108 });109 pack();
//使窗口可見110 setVisible(true);111 }
//實現接口的抽象方法,處理單擊按鈕的事件112 public void actionPerformed(ActionEvent ae)113 {114 if(ae.getSource()==start)115 ticker.start();116 else117 if(ae.getSource()==stop)118 ticker.stop();119 120 }121 public static void main(String[] args)122 {new TickerFrame();}123 }
運行:
單擊“Start”按鈕,文本就會向左移動,單擊“Stop”按鈕,則移動停止;當所有文本移到窗口之外時,文本復位,再次向左移動。
新聞熱點
疑難解答