我正在尝试制作一个简单的动画,其中一个矩形从屏幕开始(在屏幕右边缘的右侧)并向左移动。因此,在本例中,我的框架的宽度为 1000,墙壁的 x 值为 1100。显然,首先,矩形不应该是
我们可见。但当矩形向左移动时,它最终应该变得可见。然而,这个动画并没有这样做。即使墙的 x 值在屏幕范围内,它也不会被渲染。
我尝试放一个println()
中的声明paintComponent()
墙的方法,我发现paintComponent()
没有被框架调用repaint()
方法。我认为当墙第一次添加到框架中时,Swing 认为由于它不在屏幕上,所以不需要渲染,因此即使墙最终出现在屏幕上,Swing 也认为它不需要渲染得到渲染。
我尝试过重新验证和无效框架和组件,但没有任何效果。请帮我解决这个问题。下面是代码:
package graphics.simpleAnimation;
public class Simple_Animation implements Runnable {
private UI ui; // The UI (frame)
private Wall wall; // Wall object that moves across the screen
private Simple_Animation() {
// Initialize the wall object (intentionally given an x value that is greater than the frame's width)
wall = new Wall(1100, 400, 200, 400);
// Initialize the UI (width is only 1000)
ui = new UI(1000, 600, "Geometry Dash");
// Add the wall to the ui (the frame)
ui.add(wall);
}
public void run() {
// Set the frame visible
ui.setVisible(true);
// Repaint the frame and move the wall
while (true) {
ui.repaint();
wall.moveWall(-2, 0);
try {
Thread.sleep(16);
} catch (InterruptedException IE) {
System.out.println(IE);
}
}
}
// Starts the program in a new thread
public static void main(String[] args) {
Simple_Animation simpleAnimation = new Simple_Animation();
new Thread(simpleAnimation).start();
}
}
package graphics.simpleAnimation;
import javax.swing.*;
import java.awt.*;
public class UI extends JFrame {
// Variables storing the width and height of the content pane (where the components are being rendered)
public int content_pane_width;
public int content_pane_height;
public UI(int frameW, int frameH, String frameTitle) {
setTitle(frameTitle);
setSize(frameW, frameH);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(null);
content_pane_width = getContentPane().getWidth();
content_pane_height = getContentPane().getHeight();
}
@Override
public void paint(Graphics g) {
super.paint(g);
}
}
package graphics.simpleAnimation;
import java.awt.*;
import javax.swing.*;
public class Wall extends JComponent {
private int wallX;
private int wallY;
private int wallW;
private int wallH;
Wall(int x, int y, int sizeX, int sizeY) {
wallX = x;
wallY = y;
wallW = sizeX;
wallH = sizeY;
setSize(getPreferredSize());
}
public void moveWall(int moveX, int moveY) {
wallX += moveX;
wallY += moveY;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(wallW, wallH);
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
setLocation(wallX, wallY);
g2d.fillRect(0, 0, wallW, wallH);
}
}