startX = startY = 0.0; endX = endY = 100.0 ; Line ln = new Line( startX, startY, endX, endY );
This constructs an object representing a straight line segment stretching from the point (0, 0) to the point (100, 100).
It does not matter which ends you call "start" and "end". This would represent the same line:
startX = startY = 100.0; endX = endY = 0.0 ; Line ln = new Line( startX, startY, endX, endY );
Here is a program that creates a drawing of many random colored lines.
import javafx.application.*; import javafx.stage.*; import javafx.scene.Scene; import javafx.scene.layout.*; import javafx.scene.shape.*; import javafx.scene.paint.*; import java.util.Random; public class RandomLines extends Application { public void start(Stage stage) { final int NUMLINES = 21; double sceneWidth=400, sceneHeight= sceneWidth*0.75; double startX, startY, endX, endY; Random rand = new Random(); Pane root = new Pane( ); Line line; for ( int j=0; j < NUMLINES; j++ ) { startX = rand.nextDouble()*sceneWidth; startY = rand.nextDouble()*sceneHeight; endX = rand.nextDouble()*sceneWidth; endY = rand.nextDouble()*sceneHeight; line = new Line( startX, startY, endX, endY ); line.setStrokeWidth( 2.0 ); if ( j%7 == 0 ) line.setStroke( Color.RED ); else if ( j%7 == 1 ) line.setStroke( Color.ORANGE ); else if ( j%7 == 2 ) line.setStroke( Color.YELLOW.darker() ); else if ( j%7 == 3 ) line.setStroke( Color.GREEN ); else if ( j%7 == 4 ) line.setStroke( Color.BLUE ); else if ( j%7 == 5 ) line.setStroke( Color.INDIGO ); else if ( j%7 == 6 ) line.setStroke( Color.VIOLET ); root.getChildren().add( line ); } Scene scene = new Scene(root, sceneWidth, sceneHeight, Color.GHOSTWHITE ); stage.setTitle("Random Lines"); stage.setScene(scene); stage.show(); } }
1. The start and end of each line segment is chosen randomly.
startX = rand.nextDouble()*sceneWidth; startY = rand.nextDouble()*sceneHeight; endX = rand.nextDouble()*sceneWidth; endY = rand.nextDouble()*sceneHeight;
Recall that nextDouble()
of class Random
returns a value 0.0 or greater and less than 1.0.
So startX
will be a value 0.0 up to a little bit less than sceneWidth
.
2. The width of the line is set with
line.setStrokeWidth( 2.0 );
3. NUMLINES
number of lines are created and added to the scene graph:
root.getChildren().add( line );
It would be impractical to use a separate reference variable for each line.
4. The line color is set with
line.setStroke( Color.RED );
The program cycles through the colors of the rainbow ( although the color VIOLET can't really be produced on an RED-GREEN-BLUE monitor). You might wish to edit the program so that it picks random RGB values for each line, or, perhaps, picks from a wider pallet of pre-defined colors.
Could this program ever produce the same picture twice?