在JComponent上绘制毛刺

时间:2013-05-10 00:38:00

标签: java swing drawing

我在绘制JComponent时遇到了这种奇怪的故障。 发生的事情是,每当我将JFrame窗口拖到监视器的边界之外时,绘图就会加速并绘制得比它应该更快。我猜它必须对摆动管理做一些事情,看起来像Jframe在屏幕外时停止绘制,并在设置在监视器屏幕范围内后以突发方式恢复。

这是我的代码:

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

}

1 个答案:

答案 0 :(得分:2)

  • 您的绘画方法中没有程序逻辑。
  • 使用浮点数(double)进行缩放,而不是像d。
  • 那样使用int
  • 将缩放数字的值基于系统时间,而不是基于代码中包含的逻辑,您无法控制它的调用速度,即绘制方法。