Почему я могу получить следующее исключение с кодом ниже?
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.Component$BltBufferStrategy.showSubRegion(Unknown Source)
at java.awt.Component$BltSubRegionBufferStrategy.show(Unknown Source)
at javax.swing.BufferStrategyPaintManager.flushAccumulatedRegion(Unknown Source)
...
Это происходит только каждый раз, когда я запускаю его, но всегда в самом начале.Я использую if(bs.contentLost()){...}
, поэтому я не понимаю, с чем это может быть связано.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.Random;
public class MLM2 extends JFrame implements ActionListener {
private final Timer timer = new Timer(20, this);
private Insets insets;
private BufferStrategy bs;
private BufferedImage drawing;
int lastW;
int lastH;
int pos = 0;
public static void main (String[] args) {
MLM2 ex = new MLM2();
}
public void actionPerformed(ActionEvent e) {
if(bs.contentsLost()) return;
Graphics2D g = null;
g = (Graphics2D)bs.getDrawGraphics();
int w = getWidth() - insets.left - insets.right;
int h = getHeight() - insets.top - insets.bottom;
if(w!=lastW || h!=lastH) {
drawing = (BufferedImage) this.createImage(w,h);
lastW = w;
lastH = h;
}
Graphics2D drawingBoard = drawing.createGraphics();
drawingBoard.setColor(Color.PINK);
drawingBoard.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
drawingBoard.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawingBoard.fillRect(0, 0, w, h);
drawingBoard.setColor(Color.RED);
drawingBoard.fillRect(pos, 100, 100, 100);
pos++;
if(pos>=w) pos=0;
g.drawImage(drawing, insets.left, insets.top, null);
drawingBoard.dispose();
if (!bs.contentsLost()) {
bs.show();
}
}
public MLM2() {
super();
setTitle("Mirror Land");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 420);
setLocationRelativeTo(null);
insets = this.getInsets();
int insetWide = insets.left + insets.right;
int insetTall = insets.top + insets.bottom;
setSize(getWidth() + insetWide, getHeight() + insetTall);
setVisible(true);
setIgnoreRepaint(true);
createBufferStrategy(2);
bs = getBufferStrategy();
drawing = (BufferedImage) this.createImage(getWidth(),getHeight());
timer.start();
}
}