为什么我得到此线程异常?

时间:2018-04-30 03:02:34

标签: java nullpointerexception java-threads

为什么在使用Graphics g工作正常时会出现此异常,但Graphics2D g2 =(Graphics2D)g不会?错误是drawLine()使用g2.draw(new Line2D);我首先假设只是放置Graphics2D g2没有初始化对象,但错误仍然发生。显然,某些东西是空的,但我无法弄清楚这与g2有什么关系。请帮忙!

Exception in thread "Thread-0" java.lang.NullPointerException
        at Triangles.Triangle_Game.drawLine(Triangle_Game.java:126)
        at Triangles.Triangle_Game.drawTriangles(Triangle_Game.java:152)
        at Triangles.Triangle_Game.render(Triangle_Game.java:78)
        at Triangles.Triangle_Game.run(Triangle_Game.java:190)
        at java.lang.Thread.run(Thread.java:745)

完整代码转储:

package Triangles;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.Point;
import java.awt.geom.Line2D;
import java.util.ArrayList;

public class Triangle_Game implements Runnable {

    // Vars
    private static ArrayList<Point> trianglePoints = new ArrayList<>();
    private static ArrayList<Point> triangleRotatedPoints = new ArrayList<>();

    private Triangle_Display display;
    private Triangles triangles;

    private int width, height, numTriangles = 20, radius = 1, radiusCirc = 600;

    private String title;
    private Thread thread;

    private boolean running = false;

    private BufferStrategy bS;
    private Graphics g;
    private Graphics2D g2 = (Graphics2D) g;

    private static int FPS = 1;

    private static Font font20; // size 20

    // Constructor
    public Triangle_Game(String title, int width, int height) {
        this.title = title;
        this.width = width;
        this.height = height;
    }

    private void init() {
        //font10 = Triangle_FontLoader.loadFont("res/fonts/Fairlight.ttf", 10);
        font20 = new Font("Arial", Font.PLAIN, 28);
        display = new Triangle_Display(title, width, height);
        triangles = new Triangles(numTriangles, radius);
        triangles.runCalculation(triangles.numTriangles, triangles.radius);
        ArrayList<Double> resArray = triangles.runLoop(); // resArray Length
        triangles.printArray(resArray);
    }

    public void program() {
        // update triangle points here
        triangles.numTriangles += 1;
    }

    private void update() {
        program();
    }

    private void render() {
        bS = display.getCanvas().getBufferStrategy();
        if (bS == null) {
            display.getCanvas().createBufferStrategy(3);
            return;
        }
        g = bS.getDrawGraphics();
        g.clearRect(0, 0, width, height);// clear screen

        // Start Draw

        drawCircle(g, width/2 - radiusCirc, height/2 - radiusCirc, radiusCirc);
        drawFillCircle(g, width/2 - 5, height/2 - 5, 5);

        g.setColor(Color.RED);

        drawTriangles(g, trianglePoints);

        g.setColor(Color.BLACK);

        Triangle_Text.drawString(g, "Radius:", 100, 100,
                false, Color.BLACK, font20);

        Triangle_Text.drawString(g, Integer.toString(radius), 200, 100,
                false, Color.BLACK, font20);

        Triangle_Text.drawString(g, "numTriangles:", 100, 150,
                false, Color.BLACK, font20);

        Triangle_Text.drawString(g, Integer.toString(triangles.numTriangles), 280, 150,
                false, Color.BLACK, font20);

        Triangle_Text.drawString(g, "Approx PI value:", 100, 200,
                false, Color.BLACK, font20);

        Triangle_Text.drawString(g, Double.toString(triangles.area), 320, 200,
                false, Color.BLACK, font20);

        // End Draw

        bS.show();
        g.dispose();
    }

    public static double translate(double var){
        var += (double)100;
        return var;

    }

    public static double stretch(double var){
        var *= (double)2;
        return var;
    }

    public void drawCircle(Graphics g, int posX, int posY, int radius) {
        g.drawOval(posX, posY, radius * 2, radius * 2);
    }

    public void drawFillCircle(Graphics g, int posX, int posY, int radius) {
        g.fillOval(posX, posY, radius * 2, radius * 2);
    }

    public void drawLine(Graphics2D g2, double x1, double y1, double x2, double y2) {
        g2.draw(new Line2D.Double(x1 + (width/2), y1 + (height/2), x2 + (width/2), y2 + (height/2)));
    }

    public void rotationMatrix2D() {
        Point origin = new Point(0, 0);
        double x = triangles.calculateBase(triangles.theta)*radiusCirc;
        double y = triangles.calculateHeight(triangles.theta)*radiusCirc;
        trianglePoints.add(new Point((int) x, (int) y));
        for (int i = 0; i < triangles.numTriangles*2; i++) {
            Point p = trianglePoints.get(i);
            double angle = Math.toRadians(triangles.theta);
            double cos = Math.cos(angle);
            double sin = Math.sin(angle);
            double cx = origin.getX();
            double cy = origin.getY();
            x = cx + ((p.x - cx) * cos) - ((p.y - cy) * sin);
            y = cy + ((p.x - cx) * sin) + ((p.y - cy) * cos);
            triangleRotatedPoints.add(new Point((int) x, (int) y));
            trianglePoints.add(i+1, triangleRotatedPoints.get(i));
        }
    }

    public void drawTriangles(Graphics g, ArrayList<Point> array) {
        rotationMatrix2D();
        Point origin = new Point(0, 0);
        for (int i = 0; i < triangles.numTriangles*2; i += 2) {
            drawLine(g2, 20, 40, 60, 80);
            /*drawLine(g2, origin.getX(), origin.getY(),
                         trianglePoints.get(i).getX(), trianglePoints.get(i).getY());
            drawLine(g2, trianglePoints.get(i).getX(), trianglePoints.get(i).getY(),
                         triangleRotatedPoints.get(i+1).getX(), triangleRotatedPoints.get(i+1).getY());
            drawLine(g2, triangleRotatedPoints.get(i+1).getX(), triangleRotatedPoints.get(i+1).getY(),
                         origin.getX(), origin.getY());*/
        }
    }

    public static ArrayList<?> del(ArrayList<?> array) {// Return an empty array so that they don't grow enormous
        if(array.size() > 0) {
            array.clear();
        }
        return array;
    }

    public static void cleanup() {
        del(trianglePoints);
    }

    public void run() {
        init();
        double timePerTick = 1000000000 / FPS;
        double delta = 0;
        long now;
        long lastTime = System.nanoTime();
        long timer = 0;
        int ticks = 0;

        while (running) {
            now = System.nanoTime();
            delta += (now - lastTime) / timePerTick;
            timer += now - lastTime;
            lastTime = now;

            if (delta >= 1) {
                update();
                render();
                cleanup();
                ticks += 1;
                delta--;
            }
            if (timer >= 1000000000) {
                System.out.println("FPS: " + ticks);
                ticks = 0;
                timer = 0;
            }
        }
        stop();
    }

    public synchronized void start() {
        if (running) {
            return;
        }
        running = true;
        thread = new Thread(this);
        thread.start();
    }

    public synchronized void stop() {
        if (!running) {
            return;
        }
        running = false;
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void printArray(ArrayList<?> array) {
        for (Object item : array) {
            System.out.println(item.toString());
        }
    }

    // Getters and Setters

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

package Triangles;

import java.util.ArrayList;

public class Triangles {

    double radius;
    int numTriangles;
    double twoTheta;
    double theta;
    double base;
    double height;
    double result;
    double halfTriangleArea;
    double triangleArea;
    double area;
    ArrayList<Double> arrayList = new ArrayList<>();

    public Triangles(int numTriangles, double radius) {
        this.numTriangles = numTriangles;
        this.radius = radius;
        init();
    }

    private void init() {
        this.twoTheta = (double)360/numTriangles;
        this.theta = (double)twoTheta/2;
    }

    // My methods

    public double calculateBase(double theta) { // SOH
        double thetaToRadians = Math.toRadians(theta);
        double base = Math.sin(thetaToRadians) * radius;
        return base;
    }

    public double calculateHeight(double theta) { // CAH
        double thetaToRadians = Math.toRadians(theta);
        double height = Math.cos(thetaToRadians) * radius;
        return height;
    }

    public double checkPythag(double base, double height) {
        double a = base;
        double b = height;
        double result = Math.sqrt(a*a + b*b);
        return result;
    }

    public double calculateArea(double base, double height) {
        double halfTriangleArea = (0.5) * base * height;
        return halfTriangleArea;
    }

    public double runCalculation(int numTriangles, double theta) {
        base = calculateBase(theta);
        height = calculateHeight(theta);
        result = checkPythag(base, height);
        halfTriangleArea = calculateArea(base, height); 
        triangleArea = 2 * halfTriangleArea;
        // C = Pi * D = Pi * 2 * r
        // A = Pi * r.^2
        area = numTriangles * triangleArea;
        // Substitute Pi for X
        // area = X * r.^2
        // if r is 1
        // area = X
        return area;
    }

    public ArrayList<Double> runLoop() {
        ArrayList<Double> resArray = new ArrayList<>();
        for (int i = 3; i < numTriangles + 1; i++) {
            // min 3 to current numTriangles amount plus one
            double twoTheta = (double)360/i;
            double theta = (double)twoTheta/2;
            double area = runCalculation(i, theta);
            double res = Math.PI - area;
            resArray.add(res);
        }
        System.out.println("resArray length: " + resArray.size() + "\n");
        return resArray;
    }

    public void printArray(ArrayList<Double> array) {
        int triangleAmount = 3;
        for (int i = 0; i < array.size(); i++) {
            System.out.println("difference PI and " + triangleAmount + " triangles: " + array.get(i));
            triangleAmount++;
            if (i >= 1) {
                double difference = Math.abs(array.get(i-1) - array.get(i));
                arrayList.add(difference);
                // absolute difference between value (i) and (i-1)
                System.out.println(difference + " | " + arrayList.size());
            }
            if (i >= 2) {
                double diffSign = arrayList.get(i-2) - arrayList.get(i-1);
                System.out.println(diffSign);
                if (diffSign < 0) {
                    System.out.println("Difference is not positive");
                    break;
                }
            }
            System.out.println("\n");
        }
    }

    // Runnable

    public static void main(String[] args) { // create an instance of class to run in main
        // min numTriangles is 3, otherwise Triangle Area does calculation not sensible
        Triangles triangles = new Triangles(3, 1);
        triangles.runCalculation(triangles.numTriangles, triangles.theta);
        System.out.println("radius: " + triangles.radius);
        System.out.println("numTriangles: " + triangles.numTriangles);
        System.out.println("twoTheta " + triangles.twoTheta);
        System.out.println("theta " + triangles.theta);
        System.out.println("base: " + triangles.base);
        System.out.println("height: " + triangles.height);
        System.out.println("checkPythag " + triangles.result + " | " + triangles.radius);
        System.out.println("halfTriangleArea: " + triangles.halfTriangleArea);
        System.out.println("triangleArea: " + triangles.triangleArea);
        System.out.println("Approximation of Pi by triangles: " + triangles.area);

        ArrayList<Double> resArray = triangles.runLoop();
        triangles.printArray(resArray);
    }   
}

0 个答案:

没有答案