0

在这段代码中有两个按钮。一个使矩形在 x 轴上向右移动,第二个使矩形在 y 轴上向下移动。我的问题是,矩形的每个先前位置都留在屏幕上,看起来矩形正在留下痕迹在它后面。有任何建议我如何清除屏幕或其他东西?

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();
}
    }
4

1 回答 1

0

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

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

    if(check)
    {
        g.setColor(Color.red);
        g.fillRect(x, y, 50, 50);
    }
}
于 2013-07-13T16:29:24.717 回答