我想使用以下代码让球在屏幕中弹跳。问题是它仅在我调整框架大小时才移动。所以我的面板方法中有我的绘图组件。当我的线程运行时,我运行一个循环,在其中移动球, hibernate 线程并重新绘制。 仅当我调整框架大小时球才会移动。 谁能帮我吗?
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) {
}
}
}
最佳答案
spelPaneel = new JPanel(); //
您的 SpelPaneel 类扩展了 JPanel,因此无需创建另一个面板。上面的代码行只是在内存中创建了一个 JPanel,但不对其执行任何操作。
bal = new Bal(spelPaneel, 50, 50, 15);
然后,您创建 Bal Thread 并将此虚拟面板传递给它,然后尝试在此虚拟面板上进行重新绘制。
相反,我猜代码应该是:
bal = new Bal(this, 50, 50, 15);
因为“this”指的是您创建的 SeplPaneel 的实际实例。
关于java - 重绘仅在调整大小后有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504285/