The program below is the answer to Deitel’s Java How to Program (9th Edition) Chapter 4 Exercise 4.1.

Question: Using loops and control statements to draw lines can lead to many interesting designs.

  1. Create the design in the left screen capture of Fig. 4.20. This design draws lines from the top-left corner, fanning them out until they cover the upper-left half of the panel.One approach is to divide the width and height into an equal number of steps (we found 15 steps worked well). The first endpoint of a line will always be in the top-left corner (0, 0). The second endpoint can be found by starting at the bottom-left corner and moving up one vertical step and right one horizontal step. Draw a line between the two endpoints. Continue moving up and to the right one step to find each successive endpoint. The figure should scale accordingly as you resize the window.
  2. Modify part (a) to have lines fan out from all four corners, as shown in the right screen capture of Fig. 4.20. Lines from opposite corners should intersect along the middle.

To compile all four classes at the same time using the command prompt, use the command

javac Lines.java LinesTest.java LinesB.java LinesBTest.java  

To run LinesTest and LinesBTest, use the command

java LinesTest LinesBTest

Below is Class LinesTest.java to test Class Lines.java

Java GUI And Graphics Case Study program
4. 1(a) Fullscreen
Java GUI And Graphics Case Study program resizable
4.1(a) Resized
Java GUI And Graphics Case Study program resizable
4.1(a)

Below is the code for the (b) part of the question – Lines fanning out from all corners of the frame

Below is Class LinesBTest.java to test Class LinesB.java

Java GUI graphics program
4. 1(b) Fullscreen
Java GUI graphics program resizable
4.1(b) Resized
Java GUI graphics program using drawline
4.1(b)

Click here to see other answers to Java How to Program.

3 Comments

  1. The class with main in it(first program) can't be the one to "extend Jpanel". This has to be the external .java class. Also, second program creates an object LineB instead of LinesB. Other than those minor errors you have the solution. Also, than you, I wanted to see the code to study it without taking the time to write it myself. Thank you.

Write A Comment