EdQ3
EdQ3

Reputation: 31

Glitch drawing on JComponent

I'm having this weird kind of glitch with drawing on an JComponent. What happens is that whenever i drag the JFrame window outside the bounds of my monitor, the drawing accelerates and draws faster than it should. I'm guessing it has to do something with swing management, seems like drawing stops once the Jframe is offscreen and resumes in a burst kind of way after being set inside the bounds of the monitor screen.

Here's my code:

package javagame;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JComponent;

/**
*
* 
*/
public class Screen extends JComponent implements Runnable{

// paintbrush for drawing.
//private Graphics internalg;
private boolean keepDrawing = true;
public Screen() {        
   super();
   startDrawing();
}

/// Draw methods
@Override
protected void paintComponent(Graphics g) {         
    super.paintComponent(g);
    //internalg = g;
    //Draw 
    //System.out.println("painted");
    drawSomething(g);
}   

@Override
public void run() {
    //Draw until manually stopped
    while(keepDrawing){
        repaint();
    try { Thread.sleep(100); }
    catch (InterruptedException ex) { }
    }
}
/**
 * Fire off thread.
 */
private void startDrawing()
{
    Thread t = new Thread(this);
    //thread ends when JFrame is closed.
    t.setDaemon(true);
    t.start();

}
/// Draw Logic ///


/// Images
int d = 2;
public void drawSomething( Graphics internalg )
{
    if (isValid()){   
        internalg.setColor(Color.BLACK);
        internalg.fillRect(0, 0, getWidth(), getHeight());//clear bg
        internalg.setFont( new Font(Font.DIALOG, Font.BOLD, 15) );
        internalg.setColor( Color.GREEN );
        internalg.drawOval( (getWidth()/2)-(d/2) , (getHeight()/2)-(d/25), d, d);
        d++;
    }
}

/// Images

}

Upvotes: 1

Views: 200

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

  • Don't have program logic in your painting methods.
  • Use floating point numbers, double, to do your scaling, not an int, like d.
  • Base the value of your scaling number on the System time, not on logic contained within code you have no control over how fast it is called, the painting methods.

Upvotes: 2

Related Questions