I declare bs and g2 variables as static. I define them in the init () method. I launch it. the compiler throws a java.lang.NullPointerException error (supposedly the pointer points to nothing) in the render () method. If the code from init () is crammed into render (), then everything works correctly. Why is the first option (below) not working ??

package mainpack; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.image.BufferStrategy; //import java.util.Timer; import javax.swing.JFrame; public class Game extends Canvas implements Runnable { private static final long serialVersionUID = 1L; public static int WIDTH = 800; //ширина public static int HEIGHT = 300; //высота public static String NAME = "Life is game"; //заголовок окна public static int x1 = 10; static Graphics2D g2; static int Y=0; static BufferStrategy bs; private boolean running; public int msec = 0; public void start() { running = true; new Thread(this).start(); // showStatus("Privet!."); } public void run() { init(); while(running) { render(); } } public void init() { bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(2); requestFocus(); return; } g2=(Graphics2D) bs.getDrawGraphics(); } public void render() { g2.setColor(Color.black); //выбрать цвет g2.fillRect(0, 0, getWidth(), getHeight()); g2.setColor(Color.red); g2.drawRect(0, 0, x1, 50); g2.drawString(g22.toString(), 0, 70); bs.show(); //показать } void kanistra(){ } public static void main(String[] args) { Game game = new Game(); game.setPreferredSize(new Dimension(WIDTH, HEIGHT)); JFrame frame = new JFrame(Game.NAME); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(game, BorderLayout.CENTER); frame.pack(); frame.setResizable(false); frame.setVisible(true); game.start(); } } 
  • returns the type of buffering 1-single (if there is) buffering, 2- double buffering, 3- triple buffering, 0 - no type of buffering is specified. I understand that) - Pavel

1 answer 1

Inside init call to getBufferStrategy() returns null , so before the code

 g2=(Graphics2D) bs.getDrawGraphics(); 

It does not come because of the early return'a.

When you run the code of the init method in render second time, the method returns non- null , there is no early return, and g2 finally gets a non-zero value.

I think it will be enough just to remove return; from the init method.

  • it worked, thanks) and is it right to do it as I did, i.e. call the methods getBufferStrategy (), bs.getDrawGraphics () once during initialization, not every time during render'e - Pavel
  • @ Pavlik: I think it should be more correct once at the beginning. But I'm not a big Swing specialist. Should in theory work. If not - go back, find out :) - VladD