Note that there are some explanatory texts on larger screens.

plurals
  1. POinstance variable's effect is hidden in Java
    primarykey
    data
    text
    <p>I'm creating a simple face using GObject class which will use GRect and GOval. I want GRect and GOval to be anchored to the same coordinates for which I described the getWidth() and getHeight() as Instance Variable. I'm not shown any error when I do so, but there is no result on the canvas. I get result only when I describe the getWidth() and getHeight() as local variables. Why are the instance variables' effect not showing up ?</p> <pre><code>/* * This is section 2 problem 2 to draw a face using GRect amnd GOval. The face is centred in the canvas. * PS: The face is scalable w.r.t. canvas. */ package Section_2; import java.awt.Color; import java.awt.Graphics; import acm.graphics.GRect; import acm.program.GraphicsProgram; /* * creates a robot face which is centered in the canvas. */ public class RobotFace extends GraphicsProgram{ private static final long serialVersionUID = 7489531748053730220L; //canvas dimensions for centering int _canvasWidth = getWidth(); int _canvasHeight = getHeight(); public void run(){ removeAll(); //to make sure multiple instances of graphic are not drawn during resize as an effect of overriding Java paint method //draw objects createFace(); } //currently only createFace() is implemented /* * creates a rect which is centred in the canvas */ private void createFace() { //canvas dimensions for centering //int _canvasWidth = getWidth(); //int _canvasHeight = getHeight(); //make the face scalable int _faceWidth = _canvasWidth / 6; int _faceHeight = _canvasHeight / 4; //to center the face int _faceX = (_canvasWidth - _faceWidth)/2; int _faceY = (_canvasHeight - _faceHeight)/2; GRect _face = new GRect(_faceX , _faceY, _faceWidth, _faceHeight); _face.setFilled(true); _face.setColor(Color.BLUE); add(_face); } /* * (non-Javadoc) * @see java.awt.Container#paint(java.awt.Graphics) * to override Java inherited paint method to retain graphic after resizing */ public void paint(Graphics g) { this.run(); super.paint(g); } } </code></pre> <p>If you uncomment the local variables for getWidth() and getHeight(), you get the Rect , else no effect on the canvas.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload