这是我的代码:
import javax.swing.*;
import java.awt.event.*;
public class Frame {
Draw d = new Draw();
JFrame f1 = new JFrame("Animation 2");
JButton bMoveRight = new JButton(">>>>");
JButton bMoveLeft = new JButton("<<<<");
public Frame() {
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setSize(800, 600);
f1.setVisible(true);
f1.setResizable(false);
f1.setLocationRelativeTo(null);
bMoveRight.setBounds(50, 450, 120, 50);
bMoveLeft.setBounds(600, 450, 120, 50);
f1.add(bMoveRight);
f1.add(bMoveLeft);
f1.add(d);
bMoveRight.addActionListener(new ButtonMoveRight());
bMoveLeft.addActionListener(new ButtonMoveLeft());
}
private class ButtonMoveRight implements ActionListener {
public void actionPerformed(ActionEvent e){
d.animateRight();
}
}
private class ButtonMoveLeft implements ActionListener {
public void actionPerformed(ActionEvent e){
d.animateLeft();
}
}
}
import javax.swing.*;
import java.awt.*;
public class Draw extends JComponent{
int x = 50;
public void paint(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(x, 150, 200, 100);
}
public void animateLeft(){
try{
while(x != 50){
x--;
repaint();
Thread.sleep(10);
}
} catch(Exception ex){
ex.printStackTrace();
}
}
public void animateRight(){
try{
while(x != 550){
x++;
repaint();
Thread.sleep(10);
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
一切都按其应有的方式进行。除了一件事。我的动画发生了,但问题是它没有显示。我制作了另一个程序,其中只有动画并且它立即开始,但在这个程序中我制作了按钮来启动动画。发生的情况是,我单击按钮,5 秒内没有任何反应(这是它到达另一侧所需的时间),5 秒后它出现在窗口的另一侧。为什么我的动画不显示?
最佳答案
强烈建议不要在“ActionListener”回调中使用 Thread.sleep()。问题如下:您的代码在与 GUI 应用程序的主线程相同的线程中调用 - 它用于绘制界面。
您需要做什么而不是调用 sleep() - 您可以延迟触发一些事件并以正确的方式处理。你必须使用像计时器这样的东西 - 可能是这个 https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
关于java - 为什么我的动画不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30967590/