Java绘图 - 需要刷新屏幕

时间:2013-07-13 16:26:25

标签: java swing jframe draw paint

在这段代码中有两个按钮。一个使矩形在x轴上向右移动,第二个使矩形在y轴上向下移动。我的问题是,矩形的每个先前位置都停留在屏幕上,看起来像是rect在它后面留下痕迹。有什么建议我怎么能清除屏幕或什么?

public class testing extends JFrame implements ActionListener{
public JButton button;
public JButton button2;
public boolean check;
public int x;
public int y;

public void paint(Graphics g){
    if(check==true){
    g.setColor(Color.red);
    g.fillRect(x, y, 50, 50);
    }
}

public void start(){
    setLayout(new FlowLayout());
    button=new JButton();
    button2=new JButton();

    button.setPreferredSize(new Dimension(50,50));
    button.setText("R"); 
    button.addActionListener(this);
    button2.setPreferredSize(new Dimension(50,50));
    button2.setText("D");
    button2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){y=y+10;check=true;repaint();}});

    add(button);
    add(button2);

    setSize(500,500);
    setVisible(true);       
}   

public void actionPerformed(ActionEvent e) {
    x=x+10;
    check=true;
    repaint();
}

public static void main(String args[]){
    testing x=new testing();
    x.start();
}
    }

1 个答案:

答案 0 :(得分:0)

我对此并不是100%肯定,但我相信您需要调用父级的paint方法,因此请将paint方法更改为:

public void paint(Graphics g)
{
    super.paint(g);

    if(check)
    {
        g.setColor(Color.red);
        g.fillRect(x, y, 50, 50);
    }
}