2012-05-25 46 views
1
class BiomeViewComponent extends JComponent { 
@Override 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    int xpos=300; 
    int ypos=300; 
    g.setColor(Color.yellow); 
    Random r = new Random(); 
    int spread = r.nextInt(2)+1; 
    System.out.println(spread); 
    if (spread==1){ 
     xpos=xpos+50; 
     g.setColor(Color.yellow); 
     g.fillRect(xpos,ypos,50,50); 
    } 
    else{ 
     ypos=ypos-50; 
     g.setColor(Color.yellow); 
     g.fillRect(xpos,ypos,50,50); 
    } 
} 

} 

我使用了paintComponent腳本的接受答案,就像上面的代碼,它的工作,但現在的問題是我如何使它不止一次繪製?使用PaintComponent重繪()

回答

2

你應該寫一個被覆蓋的的paintComponent功能裏面你的繪圖代碼,類似:

class BiomeViewComponent extends JComponent { 
    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 

     // your painting code goes here 
    } 
} 

,然後將此喜歡的東西添加到您的JFrame:

JFrame j = new JFrame(); 
BiomeViewComponent bv=new BiomeViewComponent(); 

Container c=j.getContentPane(); 
c.setLayout(new BorderLayout()); // whatever layout you want here..... 
c.add(bv); 

的BiomeViewComponent將得到重新粉刷隨時搖擺(即它會爲你打電話paintComponent(..)功能)

請注意,這是一個很好的做法,把你的pa在JFrame以外的組件中引入代碼 - 這使您可以靈活地在構建GUI時根據需要使用JFrame重新定位查看組件。

+0

謝謝你!我感謝幫助! – BaconMan97

+0

好的問題...我現在如何讓它重漆? – BaconMan97

相關問題