在這個簡單的代碼示例反彈球的動畫:Java代碼簡單的動畫只能運行在Windows
import javax.swing.JApplet;
import javax.swing.JFrame;
import java.awt.*;
public class GraphicsMovement extends JApplet
{
public static void pause()
{
try {
Thread.sleep(10);
} catch(InterruptedException e) {
}
}
public static void main(String args[])
{
JApplet example = new GraphicsMovement();
JFrame frame = new JFrame("Movement");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(example);
frame.setSize(new Dimension(500,300)); //Sets the dimensions of panel to appear when run
frame.setVisible(true);
}
public void paint (Graphics page)
{
int width = getWidth(); // width = the width of the panel which appears when run
int height = getHeight(); // height = the height of the panel which appears when run.
//Changes background color to a blueish color
page.setColor(new Color (140,214,225));
page.fillRect(0,0,width,height);
for(int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 100; j++)
{
page.setColor(Color.YELLOW);
page.fillOval(100,55 + j,100,100); //draws a yellow oval
pause();
page.setColor(new Color (140,214,225));
page.fillOval(100,55 + j,100,100); //draws a blueish oval over the yellow oval
}
for (int k = 100; k >= 0; k--)
{
page.setColor(Color.YELLOW);
page.fillOval(100,55 + k,100,100); //draws a yellow oval
pause();
if (k != 0)
{
page.setColor(new Color (140,214,225)); //draws a blueish oval over the yellow oval
page.fillOval(100,55 + k,100,100);
}
}
}
}
}
動畫繪製精美,運行(使用JCreator中)在Windows機器上,但會不能在用IntelliJ或Eclipse編譯的Mac OS X上運行。嘗試過兩種不同的OS X機器,並且都會繪製球和背景(經過漫長的等待),但不會繼續進行動畫。
在這裏,我缺少某種平臺特定的代碼嗎? 謝謝!
在EDT _Don't_睡眠; _do_參見[* Swing *中的併發性](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/),特別是[*初始線程*](http://docs.oracle.com/ javase/tutorial/uiswing/concurrency/initial.html).. – trashgod
對不起,我還是新來的java ......這是因爲慣例還是事實上,美國東部時間沉睡導致這些特殊問題?我閱讀了這些鏈接,但我不確定爲什麼線程在這個具體示例中很重要。 – kmypwn
@kmypwn:您不需要'Thread.sleep()',而需要使用[javax.swing.Timer](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer。 HTML)。這是一個很棒的[示例](http://stackoverflow.com/a/9852739/1057230)。線程與您的具體示例無關,線程與整個Swing相關,這就是爲什麼@trashgod提到的那兩個鏈接。 –