我正在寫一個使用swing的java應用程序,其中我需要在正方形上方繪製網格。爲此,我使用Graphics
類提供的drawLine(...)
方法。Java Swing:drawLine非常慢
一切工作正常,但它需要大量的時間繪製每一行(超過20秒50行...)。我甚至可以看到實時繪製的線條。奇怪的是,水平線的繪製方式比垂直線快(幾乎立即)。
我可能會做錯事。這是網格的代碼。
public void drawGrid(Graphics g){
g.setColor(new Color(255, 255, 255, 20));
int width = getWidth();
int height = (int) (width * Utils.PLATE_RATIO);
int step = pixelSize*gridSpacing;
Color bright = new Color(255, 255, 255, 100);
Color transparent = new Color(255, 255, 255, 20);
for(int ix = insets.left + step;
ix < width; ix += step){
if(((ix - insets.left)/step) % 10 == 0){
g.setColor(bright);
}
else{
g.setColor(transparent);
}
g.drawLine(ix, insets.top, ix, height+insets.top);
}
for(int iy = insets.top+step;
iy < (insets.top + height); iy += step){
if(((iy - insets.top)/step) % 10 == 0){
g.setColor(bright);
}
else{
g.setColor(transparent);
}
g.drawLine(insets.left, iy, width + insets.left, iy);
}
}
這是因爲你沒有使用雙緩衝。見http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html –
當然,我怎麼會這麼愚蠢。謝謝 ! – Nicolas
@SureshKumar擺動組件默認是雙緩衝...... – kleopatra