4-2 Designing Graphical Objects

Recall 4-1 Q1 asked you to draw two random lines within your custom JPanel.  The odd behaviour you should have noticed was that new random lines are generated each time the paintComponent() method is called; i.e., when the window is resized.

Your code might have looked something like this:

But what if we want to generate a random pattern of lines and then maintain the same pattern even as the window is resized?  For that, we will use objects to store the attributes of each line between calls to paintComponent().

Let’s create a class to represent a Line:

This is a very simple class that includes a constructor to initialize the values of the private instance variables: x1, y1, x2, y2, and color.  Apart from that, it includes a method called draw() to enable a Line object to draw itself given the Graphics parameter, g.

Next, as usual, we create a custom JPanel:

On line 8 we create an array called lines to store 10 Line objects.  The reason it’s a private instance variable is that lines is accessed by both methods in the DrawPanel class.  The constructor randomly generates the coordinates and colours for 10 Line objects and stores references to them in the lines array.  Rather than using Math.random() to generate random integers I’ve used the Random class – we first used this class in U3-5.

The paintComponent() method simply calls the draw() method for each Line object in the lines array.  Since we are no longer generating new lines in paintComponent() but redrawing the ones in the lines array, the state of each Line object is preserved between calls to paintComponent().

Below is a TestDraw class.  Try resizing the window and see what (doesn’t) happen!

You Try!

  1. In U2 you worked on building a FillableShape hierarchy to represent Rectangle and Oval objects.  Use what you learned about abstract classes and methods, inheritance, and polymorphism to create a class hierarchy for Line, Rectangle, and Oval objects, including a draw() method for each shape type.  Build your shape hierarchy based on the UML diagram below:

    Create a DrawPanel class to generate a random mixture of 10 shapes like so:

    Notes:

    1. FillableShape methods getUpperLeftX() and getUpperLeftY() should return the smaller of the x1, x2 and y1, y2 values respectively.
    2. FillableShape methods getWidth() and getHeight() should return the absolute difference between the x1, x2 and y1, y2
    3. Enhance the DrawPanel class such that it uses an ArrayList to store a random mixture of 10 (in total) Line, Oval, and Rectangle objects generated in the constructor.  Use polymorphism so that only one ArrayList is required.