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(); } }