2013-12-10 36 views
0

我想用以下代碼讓球在屏幕中彈跳。問題是隻有在調整框架大小時纔會移動。所以我在我的面板方法中使用我的paintcomponent。當我的線程運行時,我運行一個循環,我移動球,睡覺線程並重新繪製。 當我調整框架大小時,球只會移動。 任何人都可以幫助我嗎?重繪僅在調整大小後才起作用

public class SpelPaneel extends JPanel { 

    private JLabel spelLabel; 
    private JPanel spelPaneel; 
    private Image background; 
    private Bal bal; 

    public SpelPaneel() { 
     spelPaneel = new JPanel(); 
     spelLabel = new JLabel("spel"); 
     add(spelLabel); 
     try { 
      background = ImageIO.read(new File("src/Main/images/background2.jpg")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     bal = new Bal(spelPaneel, 50, 50, 15); 
     bal.start(); 
    } 

    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.drawImage(background, 0, 0, getWidth(), getHeight(), null); 
     bal.teken(g, Color.red); 
    } 
} 

class Bal extends Thread { 

    private JPanel paneel; 
    private int x, y, grootte; 
    private int dx, dy; 
    private boolean doorgaan; 

    public Bal(JPanel paneel, int x, int y, int grootte) { 
     this.paneel = paneel; 
     this.grootte = grootte; 
     this.x = x; 
     this.y = y; 
     dy = 2; 
     doorgaan = true; 
    } 

    public int getX() { 
     return x; 
    } 

    public int getY() { 
     return y; 
    } 

    public void setX(int x) { 
     this.x = x; 
    } 

    public void setY(int y) { 
     this.y = y; 
    } 

    public void run() { 
     while (doorgaan) { 
      paneel.repaint(); 
      slaap(10); 
      verplaats(); 
     } 
    } 

    public void teken(Graphics g, Color kleur) { 
     g.setColor(kleur); 
     g.fillOval(x, y, 15, 15); 
    } 

    public void verplaats() { 
     if (x > 335 || x < 50) { 
      dx = -dx; 
     } 
     if (y > 235 || y < 50) { 
      dy = -dy; 
     } 

     x += dx; 
     y += dy; 
     setX(x); 
     setY(y); 
    } 

    private void slaap(int millisec) { 
     try { 
      Thread.sleep(millisec); 

     } catch (InterruptedException e) { 
     } 
    } 
} 
+0

我注意到你沒有同步由一個線程讀取並由另一個線程寫入的變量。我建議你讓'x'和''''volatile''。 –

+0

你可以在你的問題中添加代碼嗎? –

+0

現在添加了完整的代碼,這個面板被添加到另一個類。另一個班級是一張卡片 – user3088394

回答

2
spelPaneel = new JPanel(); // 

你SpelPaneel類,所以沒有必要創建另一個面板擴展JPanel。上面的代碼行只是在內存中創建了一個JPanel,但卻沒有做任何事情。

bal = new Bal(spelPaneel, 50, 50, 15); 

然後創建您的巴爾主題,並通過這個假面板給它,然後又試圖做到這一點的假面板上重繪。

這一翻譯我猜的代碼應該是:

bal = new Bal(this, 50, 50, 15); 

,因爲「這」指的是您創建的SeplPaneel的實際情況。

+0

非常感謝,這做了這項工作。應該知道這一點。還要感謝其他人的幫助 – user3088394

相關問題