Skip to main content
Engineering LibreTexts

3.7: Drawing Lines and Defining Graphical Methods (Optional)

  • Page ID
    58001
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    We used a Graphics object in the previous chapter to draw rectangles and ovals in a JFrame window. The Graphics class also possesses a method for drawing a line segment. Problems involving drawing pictures in an JFrame window using a series of line segments can be a source of examples of defining useful methods and also of making good use of loops.

    The Graphics class has a public instance method with the header:

    public  void  drawLine(int x1, int y1, int x2, int y2)

    The method call g.drawLine(x1, y1, x2, y2) draws a line from the point \((x1,y1)\) to \((x2,y2)\) where \((x,y)\) refers to a point that is \(x\) pixels from the left edge of the area that g is drawing in and \(y\) pixels from the top edge. Thus g.drawLine(10, 10, 10, 60) draws a vertical line segment that is 50 pixels long and is 10 pixels from the left edge of the drawing area, that is, a line segment from the point \((10,10)\) to the point \((10,60)\).

    Consider the problem of creating an Swing program with a method called drawSticks() to draw any specified number of vertical line segments. This method might be useful for an graphical user interface to the OneRowNim game to draw the number of sticks at a given point in a game. Suppose that this method must have an int parameter to specify the number of vertical lines to draw and two int parameters to specify the location of the top endpoint of the left most line segment. The drawSticks() method will need to use a Graphics object connected to the JFrame window for drawing the line segment. The only such Graphics object available is the parameter in the paint() method of the Canvas. Thus the method must have a Graphics parameter and it will be called in the paint() method using the Graphics object there as an argument. Thus the header of the method should look like:

    public void drawSticks(Graphics g,int x,int y,int num)

    The length of the line segments and and the distance between them are not specified by parameters so we need to choose some fixed values for these quantities. Let us assume that the line segments are 10 pixels apart and 50 pixels long. We now have enough information to complete the definition of an applet to solve this problem. Such a class definition is reproduced in Figure [fig-drawsticksprog].

    /** DrawLineCanvas   demonstrates some graphics commands.
     *It draws a set of 12 vertical lines and a set of 7 lines.
     */
    import java.awt.*;
    import javax.swing.JFrame;
    
    public class DrawSticksCanvas extends Canvas
      /** drawSticks(g,x,y,num) will draw num vertical line
       * segments.  The line segments are 10 pixels apart and
       * 50 pixels long. The top endpoint of the left most
       *line segment is at the point (x,y).
       */
      public void drawSticks(Graphics g, int x, int y, int num)
      {   int k = 0;
          while (k < num)
          {   g.drawLine(x, y, x, y + 50);
              x = x + 10;
              k = k + 1;
          } // while
      } // drawSticks()
    
      public void paint(Graphics g)
      {   drawSticks(g, 25, 25, 12);
          g.setColor(Color.cyan);
          drawSticks(g, 25, 125, 7);
      } // paint()
    
       
    } // DrawSticksCanvas

    Note that the body of drawSticks() uses a while-loop to draw the lines and declares and initializes a local variable to zero to use for counting the number of lines drawn. The statement g.drawLine(x, y, x, y + 50); draws a vertical line which is \(50\) pixels long. Increasing the value of \(x\) by \(10\) each time through the loop moves the next line \(10\) pixels to the right.

    The first call to drawSticks() in the paint() method draws \(12\) lines with \((25,25)\) the top point of the left-most line. The second call to drawSticks() will draw \(7\) cyan sticks \(100\) pixels lower. Note that changing the color of g before passing it as an argument to drawSticks() changes the drawing color.

    An image of the DrawSticksCanvas as it appears in a window is shown in Figure [fig-drawstickseps].

    As we have seen in this example, defining methods with parameters to draw an object makes the code reusable and makes it possible to draw a complex scene by calling a collection of simpler methods. It is a typical use of the divide-and-conquer principle. The while-loop can be useful in drawing almost any geometrically symmetric object.

    accessor method

    class scope

    formal parameter

    if statement

    if/else statement

    inherit

    local scope

    loop structure

    method overloading

    method signature

    mutator method

    multiway selection

    override

    polymorphism

    repetition structure

    scope

    selection

    side effect

    while statement

    while structure

    A formal parameter is a variable in a method declaration. It always consists of a type followed by a variable identifier. An argument is a value that is passed to a method via a formal parameter when the method is invoked. A method’s parameters constrain the type of information that can be passed to a method.

    When an argument of primitive type is passed to a method, it cannot be modified within the method. When an argument of reference type is passed to a method, the object it refers to can be modified within the method.

    Except for void methods, a method invocation or method call is an expression which has a value of a certain type. For example, nim.getSticks() returns a int value.

    The signature of a method consists of its name, and the number, types, and order of its formal parameters. A class may not contain more than one method with the same signature.

    A constructor is a method that is invoked when an object is created. If a class does not contain a constructor method, the Java compiler supplies a default constructor.

    Restricting access to certain portions of a class is a form of information hiding. Generally, instance variables are hidden by declaring them private. The class’s public methods make up its interface.

    The if statement executes a statement only if its boolean condition is true. The if-else statement executes one or the other of its statements depending on the value of its boolean condition. Multiway selection allows one and only one of several choices to be selected depending on the value of its boolean condition.

    The while statement is used for coding loop structures that repeatedly execute a block of code while a boolean condition is satisfied.

    A method declaration defines the method by specifying its name, qualifiers, return type, formal parameters, and its algorithm, thereby associating a name with a segment of executable code. A method invocation calls or uses a defined method.

    A formal parameter is a variable in the method declaration, whose purpose is to store a value while the method is running. An argument is a value that is passed to a method in place of a formal parameter.

    The following code declares two instance variables for names of players and defines a setName() method:

    private String nameOne = "Player One";
    private String nameTwo = "Player Two";
    
    public void setNames(String name1, String name2)
    {    nameOne = name1;
         nameTwo = name2;
    }

    Of course, there are many other appropriate names for the variables and parameters and other initial assignments.

    A method call that sets the names of the players of game1 is:

    game1.setNames("Xena","Yogi");

    A constructor cannot have a return type, such as void.

    One definition for the method is:

    public OneRowNim(int sticks)
    {    nSticks = sticks;
         player = 2;
    }

    The following would be displayed on the screen:

       1
       20
       false

    One definition for the method is:

    public int getMoves()
    {   return nMoves;
    }

    One definition for the method is:

    public boolean playerOneIsNext()
    {   return (player == 1);
    }

    See Figure 3.21.

    if (isHeavy == true)
         System.out.println("Heavy") ;
    else ;  // Error (remove this semicolon)
         System.out.println("Light");
    
    if (isLong == true)
         System.out.println("Long") 
    else   // Error (end line above with semicolon)
         System.out.println("Short");
    public String getPlayerName()
    {    if (player == 1)
             return "Ann";
         else if (player == 2)
             return "Bill";
         else if (player == 3)
             return "Cal";
         else
             return "Error";
    }

    When passing an argument for a primitive type, a copy of the argument’s value is passed. The actual argument cannot be changed inside the method. When passing a reference to an object, the object can be changed within the method.

    public int sumCubes(int min, int max)
    {
        int num = min;
        int sum = 0;
        while (num <=  max) { // While num <= max
            sum = sum + num*num*num; // Add cube of num to sum
            num = num + 1;       // Add 1 to num
        } //while
        return sum;           // Return the sum
    }

    Fill in the blanks in each of the following sentences:

    =14pt

    When two different methods have the same name, this is an example of


     .

    Methods with the same name are distinguished by their


     .

    A method that is invoked when an object is created is known as a


    method.

    A method whose purpose is to provide access to an object’s instance variables is known as an


    method.

    A boolean value is an example of a


    type.

    A OneRowNim variable is an example of a


    type.

    A method’s parameters have


    scope.

    A class’s instance variables have


    scope.

    Generally, a class’s instance variables should have


    access.

    The methods that make up an object’s interface should have


    access.

    A method that returns no value should be declared


     .

    Java’s if statement and if-else statement are both examples of


    control structures.

    An expression that evaluates to either true or false is known as a


     .

    In an if-else statement, an else clause matches


     .

    The ability to use a superclass method in a subclass is due to Java’s


    mechanism.

    The process of redefining a superclass method in a subclass is known as


    the method.

    =11pt

    Explain the difference between the following pairs of concepts:

    Parameter and argument.

    Method definition and method invocation.

    Local scope and class scope.

    Primitive type and reference type.

    Access method and constructor method.

    Translate each of the following into Java code:

    If b1 is true, then print “one”; otherwise, print “two”.

    If b1 is false and if b2 is true, then print “one”; otherwise, print “two”.

    If b1 is false and if b2 is true, then print “one”; otherwise, print “two”, or print “three”.

    Identify and fix the syntax errors in each of the following:

    if (isWalking == true) ;
        System.out.println("Walking");
    else
        System.out.println("Not walking");
    if (isWalking)
         System.out.println("Walking")
    else
         System.out.println("Not walking");
    if (isWalking)
         System.out.println("Walking");
    else
         System.out.println("Not walking")
    if (isWalking = false)
         System.out.println("Walking");
    else
         System.out.println("Not walking");

    For each of the following, suppose that isWalking is true and isTalking is false (first draw a flowchart for each statement and then determine what would be printed by each statement):

    if (isWalking == false)
         System.out.println("One");
         System.out.println("Two");
    if (isWalking == true)
         System.out.println("One");
         System.out.println("Two");
    if (isWalking == false)
    {
         System.out.println("One");
         System.out.println("Two");
    }
    if (isWalking == false)
         if (isTalking == true)
             System.out.println("One");
         else
             System.out.println("Two");
    else
         System.out.println("Three");

    Show what the output would be if the following version of main() were executed:

    public static void main(String argv[])
    {
         System.out.println("main() is starting");
         OneRowNim game1;
         game1  = new OneRowNim(21);
         OneRowNim game2;
         game2 = new OneRowNim(8);
         game1.takeSticks(3);
         game2.takeSticks(2);
         game1.takeSticks(1);
         game1.report();
         game2.report();
         System.out.println("main() is finished");
    }

    Determine the output of the following program:

    public class Mystery
    {
         public String myMethod(String s)
         {
             return("Hello" + s);
         }
         public static void main(String argv[])
         {
             Mystery mystery = new Mystery();
             System.out.println( mystery.myMethod(" dolly");
         }
    }

    Write a boolean method—a method that returns a boolean—that takes an int parameter and converts the integers 0 and 1 into false and true, respectively.

    Define an int method that takes a boolean parameter. If the parameter’s value is false, the method should return 0; otherwise, it should return 1.

    Define a void method named hello that takes a single boolean parameter. The method should print “Hello” if its parameter is true; otherwise, it should print “Goodbye”.

    Define a method named hello that takes a single boolean parameter. The method should return “Hello” if its parameter is true; otherwise it should return “Goodbye”. Note the difference between this method and the one in the previous exercise. This one returns a String. That one was a void method.

    Write a method named hello that takes a single String parameter. The method should return a String that consists of the word “Hello” concatenated with the value of its parameter. For example, if you call this method with the expression hello("dolly"), it should return “hello dolly”. If you call it with hello("young lovers wherever you are"), it should return “hello young lovers wherever you are”.

    Define a void method named day1 that prints “a partridge in a pear tree”.

    Write a Java application program called TwelveDays that prints the Christmas carol “Twelve Days of Christmas.” For this version, write a void method named intro() that takes a single String parameter that gives the day of the verse and prints the intro to the song. For example, intro("first") should print, “On the first day of Christmas my true love gave to me”. Then write methods day1(), day2(), and so on, each of which prints its version of the verse. Then write a main() method that calls the other methods to print the whole song.

    Define a void method named verse that takes two String parameters and returns a verse of the Christmas carol “Twelve Days of Christmas.” For example, if you call this method with verse("first", "apartridge in a pear tree"), it should return, “On the first day of Christmas my true love gave to me, a partridge in a pear tree”.

    Define a void method named permute, which takes three String parameters and prints out all possible arrangements of the three strings. For example, if you called permute("a", "b", "c"), it would produce the following output: abc, acb, bac, bca, cab, cba, with each permutation on a separate line.

    Design a method that can produce limericks given a bunch of rhyming words. That is, create a limerick template that will take any five words or phrases and produce a limerick. For example, if you call

    limerick("Jones","stones","rained","pained","bones");

    your method might print (something better than)

    There once a person named Jones
    Who had a great liking for stones,
    But whenever it rained,
    Jones' expression was pained,
    Because stones weren't good for the bones.

    For each of the following exercises, write a complete Java application program:

    Define a class named Donor that has two instance variables, the donor’s name and rating, both of which are Strings. The name can be any string, but the rating should be one of the following values: “high,” “medium,” or “none.” Write the following methods for this class: a constructor, Donor(String,String), that allows you to set both the donor’s name and rating; and access methods to set and get both the name and rating of a donor.

    Challenge. Define a CopyMonitor class that solves the following problem. A company needs a monitor program to keep track of when a particular copy machine needs service. The device has two important (boolean) variables: its toner level (too low or not) and whether it has printed more than 100,000 pages since its last servicing (it either has or has not). The servicing rule that the company uses is that service is needed when either 100,000 pages have been printed or the toner is too low. Your program should contain a method that reports either “service needed” or “service not needed” based on the machine’s state. (Pretend that the machine has other methods that keep track of toner level and page count.)

    Challenge. Design and write an OldMacdonald class that sings several verses of “Old MacDonald Had a Farm.” Use methods to generalize the verses. For example, write a method named eieio() to “sing” the part of the verse. Write another method with the signature hadAnX(String s), which sings the “had a duck” part of the verse, and a method withA(String sound) to sing the “with a quack quack here” part of the verse. Test your class by writing a main() method.

    Suppose you have an Object A, with public methods a(), b(), and private method c(). And suppose you have a subclass of A named B with methods named b(), c() and d(). Draw a UML diagram showing the relationship between these two classes. Explain the inheritance relationships between them and identify those methods that would be considered polymorphic.

    Consider the definition of the class C. Define a subclass of C named B that overrides method m1() so that it returns the difference between m and n instead of their sum.

         public class C {
             private int m;
             private int n;
             public C(int mIn, int nIn) {
                 m = mIn;
                 n = nIn;
             }
             public int m1() {
                 return m+n;
             }
         }

    This page titled 3.7: Drawing Lines and Defining Graphical Methods (Optional) is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.