动画没有按预期工作
Animation doesn't work as expected
我想移动一个矩形,它移动了,但移动时矩形变大了。 (我没有10个声望给你看截图)
我真的不知道我做错了什么,这是我的源代码:
Class Paddle.java
package ma.Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Paddle extends JPanel implements ActionListener{
int x = 0, velX = 2;
Timer t = new Timer(5, this);
public Paddle() {
// TODO Auto-generated constructor stub
}
@Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.BLACK);
g.fillRect(x, 30, 50, 30);
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
x = x + velX;
repaint();
}
}
Class Frame.java 我将面板添加到框架的位置。
package ma.Game;
import javax.swing.JFrame;
public class Frame extends JFrame
{
public Frame() {
// TODO Auto-generated constructor stub
setTitle("Game");
setSize(300, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
add(new Paddle());
}
}
您正在呼叫
super.paintComponents(g);
这会导致之前调用 paintComponent
的绘画保持可见。而是使用
super.paintComponent(g);
重绘容器背景
我想移动一个矩形,它移动了,但移动时矩形变大了。 (我没有10个声望给你看截图)
我真的不知道我做错了什么,这是我的源代码:
Class Paddle.java
package ma.Game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Paddle extends JPanel implements ActionListener{
int x = 0, velX = 2;
Timer t = new Timer(5, this);
public Paddle() {
// TODO Auto-generated constructor stub
}
@Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.BLACK);
g.fillRect(x, 30, 50, 30);
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
x = x + velX;
repaint();
}
}
Class Frame.java 我将面板添加到框架的位置。
package ma.Game;
import javax.swing.JFrame;
public class Frame extends JFrame
{
public Frame() {
// TODO Auto-generated constructor stub
setTitle("Game");
setSize(300, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
add(new Paddle());
}
}
您正在呼叫
super.paintComponents(g);
这会导致之前调用 paintComponent
的绘画保持可见。而是使用
super.paintComponent(g);
重绘容器背景