我想用以下代碼讓球在屏幕中彈跳。問題是隻有在調整框架大小時纔會移動。所以我在我的面板方法中使用我的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) {
}
}
}
我注意到你沒有同步由一個線程讀取並由另一個線程寫入的變量。我建議你讓'x'和''''volatile''。 –
你可以在你的問題中添加代碼嗎? –
現在添加了完整的代碼,這個面板被添加到另一個類。另一個班級是一張卡片 – user3088394