如何在JFrame上更新新图像? (我尝试了一切,但它没有工作)

时间:2016-06-02 05:36:02

标签: java swing

所以这是我的源代码,我试图让棍子男人首先移动,我试图让头部移动。它有效,但问题是过去的运动和背叛运动粘在一起所以它就像这个OOOOOOOOOOO它应该像这样的O

我尝试了repaint()validate()updateUI()但它仍然无法正常工作

任何想法?

    package JamesTestPackage;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;

    import javax.swing.*;
    public class StickmanUI extends JPanel implements ActionListener, KeyListener{
Timer t = new Timer(1,this);
int x=180;
int x_vel = 0;
int y_vel = 0;
public StickmanUI(){
    t.start();
    addKeyListener(this);
    setFocusable(true);
}
public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;

    g2.setStroke(new BasicStroke(5));

    g2.drawLine(200, 50, 200, 100); // body

    g2.drawLine(200, 100, 220, 150); // right leg

    g2.drawLine(200, 100, 180, 150); // left leg

    g2.drawLine(200, 75, 170, 100); //left arm

    g2.drawLine(200, 75, 230, 100); //right arm

    g2.drawOval(x, 10, 40, 40); // head


}
@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    x= x + x_vel;
    repaint();
}
@Override
public void keyPressed(KeyEvent arg0) {
    // TODO Auto-generated method stub
    if(arg0.getKeyCode()==KeyEvent.VK_RIGHT)
        x_vel = 1;
    else if(arg0.getKeyCode() == KeyEvent.VK_LEFT)
        x_vel = -1;

}
@Override
public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub
    x_vel =0;
}
@Override
public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub

}
}

1 个答案:

答案 0 :(得分:0)

在进行自定义绘制时,paintComponent()方法中的第一个语句应为:

super.paintComponent(g);

确保在完成绘画之前清除背景。

阅读Custom Painting上Swing教程中的部分,了解更多信息和工作示例,以便开始使用。