Subclassing java.awt.Rectangle

edited November 2013 in Programming Questions

Hi, I thought I would subclass Rectangle to create a button class, because Rectangle provides some usefull functions. Unfortunately, Rectangle uses the variables width and height. Is there a way to access the processing global width and height from inside a Rectangle subclassed object?

So far, when accessing width I won't get the window width, but the width of the rectangle (which i thought was only accessible with this.width). How can i access them properly? Or is there an alternative way to subclass than:

class GuiElement extends java.awt.Rectangle{
  GuiElement(int x_, int y_, PImage img, PImage hoverImg, Integer width_, Integer height_) {
    super(x_, y_, width_, height_);
    pixelImage = img;
    pixelHoverImage = hoverImg;
    vectorImage = null;
  }
}

thanks for any pointers!

Comments

  • edited November 2013

    Modern coding practice advice to avoid sub-classing in favor of composition.

    Ie. let your GuiElement not to be a Rectangle, but rather to hold a Rectangle field, to manage its geometrical needs.

    class GuiElement {
      java.awt.Rectangle geometry;
    
      GuiElement(int x_, int y_, PImage img, PImage hoverImg, Integer width_, Integer height_) {
        geometry = new java.awt.Rectangle(x_, y_, width_, height_);
        pixelImage = img;
        pixelHoverImage = hoverImg;
        vectorImage = null;
      }
    }
    

    For the record, there is still a way to access the original enclosing class' members:

    void setup()
    {
      size(800, 800);
    
      Elt e = new Elt();
      println(e.get());
    }
    
    class Elt
    {
      int width;
    
      Elt()
      {
        width = 10;
      }
    
      int get()
      {
        return TheSketchName.this.width;
      }
    }
    

    TheSketchName is the name under which you saved the sketch, it is the name of this sub-class of PApplet.

  • edited November 2013

    Thanks for clarification! Using a separate object to hold the geometry was actually the second approach I thought about implementing.

  • edited November 2013

    Additional tips:

    When extending a class, be aware that field and method names can possibly clash w/ the 1s from Processing! (~~)
    In your case, Processing's own width & height fields were overshadowed by the 1s provided by Rectangle class
    inside your new sub-class! >:)

    Anyways, a Processing's sketch extends PApplet class. That's where all those methods & fields come from! :bz
    And any classes we create, by default, are inner nested classes from the main sketch; which is the top-class! :@)

  • edited November 2013

    GoToLoop:

    When extending a class, be aware that field and method names can possibly clash w/ the 1s from Processing!

    I was aware of that, hence my initial question :)

    But thanks for the further details. Will keep that in mind. btw. nice halloween outfit :P

Sign In or Register to comment.