Java Swing : drawLine very slow
doublebuffered, fullscreen, graphics, java, swing
Solution
The code you have posted is fine, there is no problems in it. Here is a working example of a component using your method (a bit simplified):
public static class MyGrid extends JComponent
{
private int step = 10;
public MyGrid ()
{
super ();
}
public Dimension getPreferredSize ()
{
return new Dimension ( 500, 500 );
}
protected void paintComponent ( Graphics g )
{
super.paintComponent ( g );
drawGrid ( g );
}
public void drawGrid ( Graphics g )
{
int width = getWidth ();
int height = getHeight ();
Color bright = new Color ( 255, 255, 255, 200 );
Color transparent = new Color ( 255, 255, 255, 100 );
for ( int ix = step; ix < width; ix += step )
{
if ( ( ix / step ) % 10 == 0 )
{
g.setColor ( bright );
}
else
{
g.setColor ( transparent );
}
g.drawLine ( ix, 0, ix, height );
}
for ( int iy = step; iy < height; iy += step )
{
if ( ( iy / step ) % 10 == 0 )
{
g.setColor ( bright );
}
else
{
g.setColor ( transparent );
}
g.drawLine ( 0, iy, width, iy );
}
}
}
I guess there is some problem outside that piece of code.
P.S. A bit an offtopic but...
I suggest you to calculate the visible part of the painting area (using either JComponent's `getVisibleRect ()` method or Graphics `g.getClip ().getBounds ()` method) and limit your paintings with only that area.
That small optimization could speedup component's painting in times if it is really large (for example with 10000x10000 pixels component's area).
Problem
I am writing a java application using swing in which I need to draw a grid above a square. In order to do so, I am using the `drawLine(...)` method provided by the `Graphics` class. Everything works fine except that it takes a lot of time to draw each line (more than 20 sec for 50 lines...). I can even see the lines being drawn in real time. One weird thing is that the horizontal lines are drawn way faster than the vertical lines (almost instantly). I might be doing something wrong. Here is the code for the grid. ``` 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); } } ```