Search code examples
javaswinggraphics2d

Calling methods to draw on JFrame


Can somebody explain to me why this isn't working? The error seems to be inside the Gen class but I think it may something to do with BoxMan. The error says cannot find symbol- variable g. I also tried putting in ints and doubles but it gives me: Required (Java.awt.Graphics) Found(int) / (double). So how can fix this? I've looked everywhere and can't find the answer. Help a beginner!

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.lang.Object.*;

       public class JFrame_Test
{
        public static void main (String [] args)
    {
         Gen Gen= new Gen (1500,1000,"A Name"); // this gives parameters for a Jframe later.
    }
}


{
     Gen (int size1, int size2, String title)
     {
     JFrame aFrame = new JFrame (title);
     aFrame.setSize(size1,size2);
     aFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
     aFrame.setVisible(true);
     //aFrame.getContentPane().add(new Canvas());
     //Was trying to get it to work with a canvas
     BoxMan.paint (g); // the error pops up here.
    }
}

public class BoxMan

{
    public Graphics2D g2;
  public void paint(Graphics a ) 
  {
     g2 = (Graphics2D) g; // i even tried declaring "g" here.
     g2.drawRect (10, 10, 200, 200); 
  }
}

Solution

  • The Graphics object isn't declared anywhere. If you want to draw on your JPanel you should rather create a class extending JPanel and there add draw() method which will get an "automated" Graphics object.

    Eventually you can create your own Graphics object but you didn't do that anywhere in that code. Your BoxMen class is very messy. You have to decide if you use Graphics object argument under paint() method or declare it yourself. I'm assuming you try the second one, if so, you should change the g to a (there isn't a g variable anywhere in BoxMen class). You can also get rid of the field g2 and use a local variable instead.

    The error pops up because Java doesn't know what you mean by g (it isn't declared anywhere). It depends on you if you want to use the JPanel's Graphics or your own.