2015-11-08 58 views
1

在下面的代碼中,我試圖從一個線程繪製一個橢圓形的paint方法和另一個橢圓。但是隻有繪製方法繪製的橢圓纔會顯示在JPanel上。如果這是不可能的,那麼請給出一個關於替代方案的想法。有什麼辦法可以在java中使用線程在JPanel上繪製圖形?

import java.awt.Graphics; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Ani extends JPanel{ 

    public Ani(){ 
     JFrame jf = new JFrame(); 
     jf.setSize(555,555); 
     jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     jf.add(this); 
     jf.setVisible(true); 
    } 

    public void paint(Graphics g){   
     g.fillOval(22,22, 55, 55); 
     Thread t = new Thread(new MyThread(g)); 
     t.start(); 
    } 

    public static void main(String[] args) { 
     new Ani(); 
    } 

} 

class MyThread extends Thread{ 
    Graphics g; 
    MyThread(Graphics g){ 
     this.g = g; 
    } 

    public void run(){ 
     g.fillOval(222, 222, 55, 55);  
    } 
} 

回答

0

試試這個

import java.awt.Graphics; 
import java.awt.Graphics2D; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Ani2 extends JPanel implements Runnable{ 
private Thread animator; 
int x=0, y=0; 
private final int DELAY = 50; 
    public Ani2(){ 
     JFrame jf = new JFrame(); 
     jf.setSize(555,555); 
     jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     jf.add(this); 
     jf.setVisible(true); 
    } 

    @Override 
    public void addNotify() { 
     super.addNotify(); 
     animator = new Thread(this); 
     animator.start(); 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2d = (Graphics2D)g; 
     g2d.fillOval(x,y, 55, 55); 
     g.dispose(); 
    } 
    public void cycle() { 

     x += 1; 
     y += 1; 
    } 

    public static void main(String[] args) { 
     new Ani2(); 
    } 

    @Override 
    public void run() { 
     long beforeTime, timeDiff, sleep; 

     beforeTime = System.currentTimeMillis(); 

     while (true) { 

      cycle(); 
      repaint(); 

      timeDiff = System.currentTimeMillis() - beforeTime; 
      sleep = DELAY - timeDiff; 

      if (sleep < 0) 
       sleep = 2; 
      try { 
       Thread.sleep(sleep); 
      } catch (InterruptedException e) { 
       System.out.println("interrupted"); 
      } 

      beforeTime = System.currentTimeMillis(); 
     } 
    } 

} 
0

編輯

所有畫一個Swing組件應該由UI線程來完成,通過的paintComponent(圖形G)方法

編輯完

如果您想要在循環中繪製動畫,您應該使用javax.swing.timer

int x = 0; 

public void paintComponent(Graphics g) { 
    g.drawString("Hello World", x * 10, 40); 
} 
//... 
public void init() { 
    //... 
    Timer t = new Timer(1000, new ActionListener() { 
    public void actionPerformed(ActionEvent ae) { 
     x = (x + 1) % 10; 
     repaint(); 
    } 
    }); 
} 
+0

謝謝您的回答。但我不想這樣做。 –

相關問題