在切换图标时形成一些原因图像闪烁。当我尝试创建对象然后尝试通过将x和y作为参数传递给对象来使它们移动时,我还有更多这个问题。任何帮助都会很棒。
public class Main extends JFrame implements ActionListener, KeyListener{
static Main main;
Render render;
Timer timer;
static int x,y,count;
ImageIcon player1 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Player1.png");
ImageIcon player2 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Player2.png");
Main(){
render = new Render();
timer = new Timer(100,this);
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
addKeyListener(this);
add(render);
timer.start();
}
public void render(Graphics g){
count += 1;
if(count < 20){
player1.paintIcon(this, g, x, y);
}
if(count > 20){
player2.paintIcon(this, g, x, y);
}
if(count > 40){
count = 0;
}
}
public static void main(String [] args){
main = new Main();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(count);
render.repaint();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int id = e.getKeyCode();
int speed = 4;
if(id == KeyEvent.VK_UP){
y -= speed;
}
if(id == KeyEvent.VK_DOWN){
y += speed;
}
if(id == KeyEvent.VK_LEFT){
x -= speed;
}
if(id == KeyEvent.VK_RIGHT){
x += speed;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
渲染课程。
public class Render extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
Main.main.render((Graphics)g);
}
}
答案 0 :(得分:0)
如果您在revalidate()
之后的动作事件中调用了repaint()
,那么可以使动画更流畅的另一件事就是。