0

when i try to compile this it gives me an error for a non-static method begin(int) cannot be referenced from a static context. Any way this can be fixed?

import java.util.Scanner;
import objectdraw.*;
import java.awt.*;
import java.util.concurrent.TimeUnit;

public class Ricochet extends WindowController
{
    private static final int CANVAS_WIDTH=400;
    private static final int CANVAS_HEIGHT=600;

    public static void main(String [] args)
    {
        Scanner scnr = new Scanner(System.in);
        System.out.println("Enter size of box in pixels: ");
        int boxSize = scnr.nextInt();
        System.out.println("Enter number of crossings: ");
        int Crossings = scnr.nextInt();
        System.out.println("Enter pixel Speed: ");
        int pixelSpeed = scnr.nextInt();
        new Ricochet().startController(CANVAS_WIDTH, CANVAS_HEIGHT);
        begin(boxSize);

    }
    private FilledRect sq1;
    public void begin(int boxSize)
    {
        sq1 = new FilledRect(1,1, boxSize, boxSize, canvas);
        sq1.setColor(Color.GREEN);
    }
}       
Nong Shim
  • 65
  • 1
  • 5

3 Answers3

0

new Ricochet().startController(CANVAS_WIDTH, CANVAS_HEIGHT); begin(boxSize);

Ricochet ricochet = new Ricochet().startController(CANVAS_WIDTH, CANVAS_HEIGHT); ricochet.begin(boxSize);

Ivan Tamashevich
  • 291
  • 1
  • 5
  • 14
0

Instead of:

new Ricochet().startController(CANVAS_WIDTH, CANVAS_HEIGHT);
begin(boxSize);

Write:

 Ricochet ricochet = new Ricochet();
 ricochet.startController(CANVAS_WIDTH, CANVAS_HEIGHT);
 ricochet. begin(boxSize);

Your instance methods need to be called from an instance. Otherwise they need to be declared as static.

You should read this for more info:Why non-static variable cannot be referenced from a static context?

Kiki
  • 2,243
  • 5
  • 30
  • 43
0

You are trying to call an instance method directly from a static context. so, compiler couldn't get to an instance method without giving it an instance reference from a static context. Not possible. so, Mark the method begin as static to make it to Class level. then, it becomes accessible from static context.

Solution is

public static void begin(int boxSize)
{
    sq1 = new FilledRect(1,1, boxSize, boxSize, canvas);
    sq1.setColor(Color.GREEN);
}

The other way is to invoke the method using the instance object

Ricochet instance = new Ricochet();
instance.startController(CANVAS_WIDTH, CANVAS_HEIGHT);
instance.begin(boxSize);

Hope you understand now clearly.

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53