我在 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
}