【发布时间】:2016-07-02 10:06:51
【问题描述】:
我正在尝试在JFrame 中使用Canvas 来实现Julia Set 的情节。出于某种原因,setColor() 似乎不起作用。这是负责的代码:
@Override
public void paint(Graphics aGraphics)
{
// store on screen graphics
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
for(int i = 0; i < m_iWidth; i++)
{
for(int j = 0; j < m_iHeight; j++)
{
int r = m_iPixelRed[i][j];
int g = m_iPixelGreen[i][j];
int b = m_iPixelBlue[i][j];
aGraphics.setColor(new Color(r, g, b));
aGraphics.drawRect(i, j, 0, 0);
}
}
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 1, 1, null);
}
起初我怀疑这些值没有正确传递给m_iPixel...,所以我在调用函数中将这些值硬编码为0xff。我通过r、g、b 进行了检查,并确定它们都设置为该值,但画布是黑色的。
有趣的是:当我输入aGraphics.setColor(Color.WHITE) 或aGraphics.setColor(0xff, 0xff, 0xff) 而不是变量r、g、b 时,它可以工作!即使我检查了变量是否具有相同的值,并且之前将它们硬编码为0xff。我完全不知道可能是什么问题......
编辑:
这些值被硬编码如下:
public void setPixelColour(int i, int j, int r, int g, int b)
{
m_iPixelRed[i][j] = 0xff;
m_iPixelGreen[i][j] = 0xff;
m_iPixelBlue[i][j] = 0xff;
}
setPixelColour在这个方法中被超类调用:
private void calcColour(int i, int j, int aIterations)
{
m_cCanvas.setPixelColour(i, j, 0XFF, 0xff, 0XFF);
}
这个循环又调用了它。
for(int i = 0; i < iCanvasHeight; i++){
for(int j = 0; j < iCanvasWidth; j++){
cSum.setRe(m_cCoordPlane[i][j].getRe());
cSum.setIm(m_cCoordPlane[i][j].getIm());
m_iIterations[i][j] = 0;
do{
m_iIterations[i][j]++;
cSum = cSum.square();
cSum = cSum.add(m_cSummand);
m_dAbsSqValues[i][j] = cSum.getAbsSq();
}while((m_iIterations[i][j] < MAXITER) && (m_dAbsSqValues[i][j] < m_iDivergThresh));
this.calcColour(i, j, m_iIterations[i][j]);
m_cMsgIter = "x = " + i + " , y = " + j;
this.repaint();
}
}
我检查并确保这个循环确实完成了。我在setColor() 之前使用调试器再次检查了这些值。由于我不信任调试器(缺乏经验),我再次检查了控制台,在 setColor() 之前添加了 System.out.println("r = " + Integer.toString(r) + " g = " + Integer.toString(g) + " b = " + Integer.toString(b));。
编辑:
这是我JFrame的绘制方法:
public void paint(Graphics aGraphics)
{
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
this.paintComponents(aGraphics);
// drawString() calls are debug code only...
aGraphics.setColor(Color.BLACK);
aGraphics.drawString(m_cSMsg, 10, 450);
aGraphics.drawString(m_cMsgIter, 10, 465);
aGraphics.drawString(m_cMsgDivThresh, 10, 480);
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 0, 0, null);
}
【问题讨论】:
-
你能展示你如何检查变量内容的代码吗?或者你是如何对它们进行硬编码的?
-
@Mr.M 当然,我编辑了上面的代码。
-
@Mr.M 好的,我找到了解决方案,但不是错误的原因。当我将
this.repaint()更改为m_cCanvas.repaint()时(呃,显然......)它可以工作。虽然这并没有改变m_cCanvas::paint()使用r == 0xff, g == 0xff, b == 0xff调用的事实,但这并不会改变屏幕的颜色。知道这怎么可能吗? -
好的,所以我尽可能地复制了您的代码并尝试自己查看。使用硬编码版本,我确实得到了一张白色的画布。显然我无法真正测试其他版本。但我没有遇到 r、g 和 b 的值与被绘制到屏幕上的值不同的情况。 (这让我相信错误一定出在其他地方)
-
您应该考虑使用 drawLine() 而不是 drawRect() 来绘制单个像素。
标签: java swing canvas graphics awt