Java Reference
In-Depth Information
L
ISTING
28.6
GraphView.java
1
import
javafx.scene.layout.Pane;
2
import
javafx.scene.shape.Circle;
3
import
javafx.scene.shape.Line;
4
import
javafx.scene.text.Text;
5
6
public class
GraphView
extends
Pane {
7
extends
Pane
Displayable vertices
private
Graph<?
extends
Displayable> graph;
8
9
public
GraphView(Graph<?
extends
Displayable> graph) {
10
this
.graph = graph;
11
12
// Draw vertices
13 java.util.List<?
extends
Displayable> vertices
14 = graph.getVertices();
15
for
(
int
i =
0
; i < graph.getSize(); i++) {
16
int
x = vertices.get(i).getX();
17
int
y = vertices.get(i).getY();
18 String name = vertices.get(i).getName();
19
20
getChildren().add(
new
Circle(x, y,
16
));
// Display a vertex
display a vertex
display a text
21
getChildren().add(
new
Text(x -
8
, y -
18
, name));
22 }
23
24
// Draw edges for pairs of vertices
25
for
(
int
i =
0
; i < graph.getSize(); i++) {
26 java.util.List<Integer> neighbors = graph.getNeighbors(i);
27
int
x1 = graph.getVertex(i).getX();
28
int
y1 = graph.getVertex(i).getY();
29
for
(
int
v: neighbors) {
30
int
x2 = graph.getVertex(v).getX();
31
int
y2 = graph.getVertex(v).getY();
32
33
// Draw an edge for (i, v)
34
getChildren().add(
new
Line(x1, y1, x2, y2));
draw an edge
35 }
36 }
37 }
38 }
To display a graph on a pane, simply create an instance of
GraphView
by passing the
graph as an argument in the constructor (line 9). The class for the graph's vertex must imple-
ment the
Displayable
interface in order to display the vertices (lines 13-22). For each
vertex index
i
, invoking
graph.getNeighbors(i)
returns its adjacency list (line 26). From
this list, you can find all vertices that are adjacent to
i
and draw a line to connect
i
with its
adjacent vertex (lines 27-34).
Listing 28.7 gives an example of displaying the graph in FigureĀ 28.1, as shown in
FigureĀ 28.10.
L
ISTING
28.7
DisplayUSMap.java
1
import
javafx.application.Application;
2
import
javafx.scene.Scene;
3
import
javafx.stage.Stage;
4
5
public class
DisplayUSMap
extends
Application {
6 @Override
// Override the start method in the Application class
7
public void
start(Stage primaryStage) {
8 City[] vertices = {
new
City(
"Seattle"
,
75
,
50
),
Search WWH ::
Custom Search