嗨,我一直在尝试通过更改我编写的绘制曼德尔布罗集的程序来搞乱 Java GUI,但是当我将 if 语句放入 Paint 方法中时,它会使图像在屏幕上闪烁,然后删除为黑屏。
这是我的绘画方法:
public void paintComponent(Graphics g)
{
if (clicked == false && count == 0)
{
drawMandelbrot(g); //sends graphics object to the method that draws the Mandelbrot set
clicked = !clicked;
}
zoom(g);
repaint();
}
public void zoom(Graphics g)
{
if (count > 0 && clicked == false)
{
g.setColor(Color.white);
g.fillRect(0,0, 400, 400);
clicked = !clicked;
}
}
我知道drawMandelbrot()函数有明显的错误,因为它以前工作过,而且我知道它不应该是zoom()函数,因为计数仅在mousePressed时增加。
有什么想法吗?我尝试过注释掉很多部分,有时它会保留在屏幕上,但我再次运行它,但它没有。 Swing/AWT 这么奇怪吗?
更新:
我发现问题与设置背景颜色有关。我在主函数中设置了框架的背景颜色,但由于某种原因(我仍然不知道)在绘制图像后,它再次设置了背景颜色。
public Mandelbrot (int w, int h) //constructor method that is only utilized to bring in the size of the screen
{
this.setBackground(Color.BLACK);
addMouseListener(this);
clicked = false;
count = 0;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (clicked == false && count == 0)
{
drawMandelbrot(g); //sends graphics object to the method that draws the Mandelbrot set
clicked = !clicked;
}
zoom(g);
}
public void zoom(Graphics g)
{
if (count > 0 && clicked == false)
{
}
}
public void mouseReleased(MouseEvent e)
{
zoomX = e.getX();
count ++;
clicked = !clicked;
repaint();
System.out.print(clicked);
}
更新2: 它仍然不起作用,它第一次起作用,但我尝试再次运行它,并且发生了与之前相同的事情,并且以黑框结束。
最佳答案
在方法调用的顶部调用 super.paintComponent()
以使 Swing 处理绘制组件的其余部分。有关 painting components in Swing 的更多信息,请参阅本文。但基本上,paintComponent()
方法正在做真正的工作,绘制您尝试显示的组件,当您覆盖它时,所有组件都会被禁用。通过调用 super.paintComponent(),您可以让 Swing 执行正确绘制所有内容所需的操作,然后它也绘制您想要绘制的内容。
更新
我想知道这是否与您关于“点击”的逻辑无关。当您调用 repaint()
时,它会从头开始重新绘制整个面板。这意味着,如果您希望某些内容随着时间的推移而持续存在,您要么需要 a) 不调用 repaint,也不让 Swing 调用 repaint,例如调整窗口大小;或者 b) 确保您的重绘方法始终绘制您想要的内容。一般来说,b) 是更好的方法,因为它更稳健。
因此,我希望您尝试重构代码,使其在 paintComponent()
方法中没有任何条件,这样无论调用它多少次,对象仍然会被绘制。
您可能遇到的问题(大概这就是您按照您的方式构建代码的原因)是构造您想要绘制的对象所需的时间可能太长,以至于无法证明始终重绘是合理的。如果这是一个问题,您需要重做程序的逻辑,以便计算要在另一个线程中绘制的内容(请参阅 SwingUtilities.invokeLater()
),然后在调用 paintComponent()
时只需绘制之前计算的值。
关于Java Paint 方法闪烁并消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4909774/