繁体   English   中英

图形g-使用油漆,如何擦除东西?

[英]Graphics g - Using paint, how do I make things erase?

我的绘画方法是这样的。

public void paint (Graphics g)
{      

    while (cardChosen != 'a');
    {
       g.drawImage (selectionBG, 0, 0, 1960, 677, null);
        g.drawImage (duelSGX, x_coordinate, y_coordinate, 483, 677, null);
        g.drawImage (Ultor, x_coordinate + 777, y_coordinate, 483, 677, null);
        g.drawImage (Seirin, x_coordinate + 777 * 2, y_coordinate, 483, 677, null);
        g.drawImage (Rowgen, x_coordinate + 777 * 3, y_coordinate, 483, 677, null);
        g.drawImage (Ronel, x_coordinate + 777 * 4, y_coordinate, 483, 677, null);
        g.drawImage (Ophelia, x_coordinate + 777 * 5, y_coordinate, 483, 677, null);
        g.drawImage (Narza, x_coordinate + 777 * 6, y_coordinate, 483, 677, null);
        g.drawImage (Michele, x_coordinate + 777 * 7, y_coordinate, 483, 677, null);
        g.drawImage (Maxwell, x_coordinate + 777 * 8, y_coordinate, 483, 677, null);
        g.drawImage (MageDEAN, x_coordinate + 777 * 9, y_coordinate, 483, 677, null);
        g.drawImage (Kuda, x_coordinate + 777 * 10, y_coordinate, 483, 677, null);
        g.drawImage (Gravion, x_coordinate + 777 * 11, y_coordinate, 483, 677, null);
    }

}

我也有这个

    if (ev.getKeyCode () == KeyEvent.VK_A)
    cardChosen = 'a';

    repaint ();

现在考虑一下,当我按“ a”键时,我痛苦中描绘的所有事物难道不应该消失吗? 没有。 图片显示,向上并且滞后。

您的paint(...)方法应为:

public void paint(Graphics g)
{
    super.paint(g); // to clear the background

    // add your code here
}

您有危险的代码:在绘画方法中有一个while (true)循环,这将使GUI陷入停顿。 绝对不要那样做。 代替

  • 使用Swing并在JPanel或JCompnent的paintComponent(...)方法中进行绘制。
  • 确保调用上级的paintComponent(...)方法。 通常,这应该是您的paintComponent方法重写的第一行,这将擦除旧图像。
  • 最重要的是, 所有绘制方法中获取所有程序逻辑,例如while循环。 所有绘制方法都必须尽可能快地使人眼花fast乱,因此您永远不要在其中希望被其他地方调用并且可能减慢其速度的代码。 此外,您永远无法完全控制是否或何时调用绘画方法,因此,如果这些方法中存在程序逻辑,它们可能会动摇。
  • 更好的方法是在paintComponent方法中具有某种if (...)块,然后在事件侦听器中更改此块的状态,然后调用repaint()
  • 无论如何,while都不应该出现在您的代码中,因为您的代码是事件驱动程序。 而是监听事件,然后做出响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM