滾動顯示文本的Java程式__Java
來源:互聯網
上載者:User
/**
* 檔案名稱:ScrollFrame.java
* 環境: GNU/Linux Ubuntu 7.04 + Eclipse 3.2 + JDK 1.6
* 功能:滾動文本顯示面板Demo
* 版本:0.0.2.0
* 版本改動:簡化了0.0.1.0版本中的原始碼,修複了開始不能顯示文本的Bug
* 作者:88250
* 日期:2007.5.3
* E-mail & MDN: DL88250@gmail.com
* QQ:845765
*/
import java.awt. * ;
import javax.swing. * ;
public class ScrollFrame extends JFrame
{
public static String[] textContent = { " This " , " is " , " a " , " simple " , " Demo! " };
public ScrollFrame()
{
super ( " Scroll Text Display by 88250 " );
ScrollPane news = new ScrollPane();
setBounds( 600 , 300 , 370 , 200 );
setResizable( false );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.setLayout( new GridLayout( 1 , 1 , 0 , 0 ));
pane.add(news);
setContentPane(pane);
setVisible( true );
}
public static void main(String[] arguments)
{
ScrollFrame scrollFrame = new ScrollFrame();
}
}
class ScrollPane extends JPanel implements Runnable
{
/**
* 參考縱座標,控制動畫效果
*/
int y;
public ScrollPane()
{
new Thread( this ).start();
}
/*
* 線上程的run裡面,它每次都會使y改變,然後調用repaint()方法,此方法會調用paint再畫一次
* 再畫一次的時候,裡面的y座標是每次都會變的,這樣就形成了一種動畫效果
*/
public void run()
{
while ( true )
{
y -= 1 ;
if (y < 0 )
{
y = 201 ;
}
try
{
Thread.sleep( 20 );
}
catch (InterruptedException e)
{
}
repaint();
}
}
public void paint(Graphics comp)
{
Graphics2D com2D = (Graphics2D) comp;
Font type = new Font( " monospaced " , Font.BOLD, 14 );
com2D.setFont(type);
com2D.setColor(getBackground());
com2D.fillRect( 0 , 0 , getSize().width, getSize().height);
com2D.setColor(Color.black);
for ( int i = 0 ; i < ScrollFrame.textContent.length; i ++ )
{
com2D.drawString(ScrollFrame.textContent[i], 5 , y + ( 20 * i));
}
}
}