To enhance your BusNetworks application with a graphical display of the town network, including interactive features such as clicking on a town to highlight its connected network, you'll need to perform several steps:
-
Modify the Data Loading Mechanism: Adapt the loadNetwork method to parse the data-with-lat-long.txt file, which includes latitude and longitude information for each town.
-
Update the Town Class: Ensure the Town class can store latitude and longitude coordinates, which will be used to position towns on the GUI.
-
Implement Graphical Display: Utilize the ecs100 library to draw towns as nodes (e.g., circles) on the GUI based on their geographical coordinates and draw connections (edges) between neighboring towns.
-
Add Interactivity: Implement mouse click listeners to detect when a user clicks on a town, then highlight all reachable towns and the paths connecting them.
Let's walk through each step in detail with corresponding code snippets.
1. Modify the Data Loading Mechanism
Assuming data-with-lat-long.txt has the following format:
<number_of_towns>
<town_name> <latitude> <longitude>
...
<town1> <town2>
...
You'll need to parse the number of towns, read each town's details, and then read the connections.
Updated loadNetwork Method
public void loadNetworkWithCoordinates(String filename) {
try {
busNetwork.clear();
UI.clearGraphics(); // Clear any previous drawings
UI.clearText();
List<String> lines = Files.readAllLines(Path.of(filename));
int numberOfTowns = Integer.parseInt(lines.remove(0).trim());
// Read each town's name and coordinates
for (int i = 0; i < numberOfTowns; i++) {
String line = lines.remove(0).trim();
String[] parts = line.split(" ");
if (parts.length >= 3) {
String name = parts[0];
double latitude = Double.parseDouble(parts[1]);
double longitude = Double.parseDouble(parts[2]);
Town town = new Town(name, latitude, longitude);
busNetwork.put(name, town);
}
}
// Read the connections
for (String line : lines) {
String[] connection = line.split(" ");
if (connection.length == 2) {
String town1 = connection[0];
String town2 = connection[1];
Town townObj1 = busNetwork.get(town1);
Town townObj2 = busNetwork.get(town2);
if (townObj1 != null && townObj2 != null) {
townObj1.addNeighbour(townObj2);
townObj2.addNeighbour(townObj1);
}
}
}
UI.println("Loaded " + busNetwork.size() + " towns with coordinates.");
drawNetwork(); // Initial draw
} catch (IOException e) {
throw new RuntimeException("Loading " + filename + " failed: " + e);
}
}
Note: Ensure that the data-with-lat-long.txt file is correctly formatted as per the above structure.
2. Update the Town Class
Modify the Town class to include latitude and longitude attributes, and optionally, GUI coordinates for drawing.
Updated Town Class
public class Town {
private String name;
private double latitude;
private double longitude;
private Set<Town> neighbours;
// GUI coordinates (computed based on latitude and longitude)
private double x;
private double y;
private static final double RADIUS = 10; // Radius for drawing towns
public Town(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.neighbours = new HashSet<>();
}
public String getName() {
return name;
}
public Set<Town> getNeighbours() {
return neighbours;
}
public void addNeighbour(Town town) {
neighbours.add(town);
}
// Getters for coordinates
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
// Getters and setters for GUI positions
public double getX() {
return x;
}
public double getY() {
return y;
}
public void setGUIPosition(double x, double y) {
this.x = x;
this.y = y;
}
// Method to check if a point is within the town's circle
public boolean containsPoint(double px, double py) {
double dx = px - x;
double dy = py - y;
return dx * dx + dy * dy <= RADIUS * RADIUS;
}
@Override
public String toString() {
return name;
}
}
3. Implement Graphical Display
Create a method drawNetwork to visualize the towns and their connections. Map latitude and longitude to GUI coordinates.
Mapping Latitude and Longitude to GUI Coordinates
To map geographical coordinates to screen pixels, you need to:
- Determine the range of latitude and longitude in your data.
- Scale these ranges to fit within your GUI window dimensions.
For simplicity, let's assume:
- GUI Window Size: 800x600 pixels
- Padding: 50 pixels on each side
drawNetwork Method
public void drawNetwork() {
UI.clearGraphics();
UI.setColor(Color.BLACK);
UI.setLineWidth(1);
// First, find the min and max of latitude and longitude
double minLat = Double.MAX_VALUE, maxLat = -Double.MAX_VALUE;
double minLong = Double.MAX_VALUE, maxLong = -Double.MAX_VALUE;
for (Town town : busNetwork.values()) {
if (town.getLatitude() < minLat) minLat = town.getLatitude();
if (town.getLatitude() > maxLat) maxLat = town.getLatitude();
if (town.getLongitude() < minLong) minLong = town.getLongitude();
if (town.getLongitude() > maxLong) maxLong = town.getLongitude();
}
// Define padding and scaling
double padding = 50;
double width = 800 - 2 * padding;
double height = 600 - 2 * padding;
double latRange = maxLat - minLat;
double longRange = maxLong - minLong;
// Compute GUI positions for each town
for (Town town : busNetwork.values()) {
double x = padding + ((town.getLongitude() - minLong) / longRange) * width;
double y = padding + ((maxLat - town.getLatitude()) / latRange) * height; // Invert y-axis for GUI
town.setGUIPosition(x, y);
}
// Draw connections first
UI.setColor(Color.LIGHT_GRAY);
UI.setLineWidth(2);
for (Town town : busNetwork.values()) {
for (Town neighbor : town.getNeighbours()) {
// To avoid drawing duplicate lines, only draw if neighbor's name is greater
if (town.getName().compareTo(neighbor.getName()) < 0) {
UI.drawLine(town.getX(), town.getY(), neighbor.getX(), neighbor.getY());
}
}
}
// Draw towns
for (Town town : busNetwork.values()) {
UI.setColor(Color.BLUE);
UI.fillOval(town.getX() - 5, town.getY() - 5, 10, 10);
UI.setColor(Color.BLACK);
UI.drawString(town.getName(), town.getX() + 5, town.getY() - 5);
}
}
Explanation:
- Coordinate Mapping: The method calculates the minimum and maximum latitude and longitude to determine the scaling factors.
- GUI Position: Each town's geographical coordinates are mapped to GUI coordinates (
x, y) with appropriate scaling and padding.
- Drawing Connections: Lines are drawn between connected towns. To prevent drawing duplicate lines (since connections are bidirectional), only draw a line if the neighbor's name is lexicographically greater.
- Drawing Towns: Each town is represented as a blue circle with its name labeled nearby.
Integrate drawNetwork in loadNetworkWithCoordinates: After loading the network, call drawNetwork() to visualize it.
4. Add Interactivity
Implement mouse click listeners to detect clicks on towns and highlight the connected network.
Step-by-Step Implementation
- Add a Mouse Listener: Detect when the user clicks on the graphical window.
- Determine Clicked Town: Check if the click was within any town's circle.
- Highlight Connected Network: If a town is clicked, find all connected towns and redraw the network, highlighting the relevant towns and connections.
Updated setupGUI Method
Add a mouse listener in the setupGUI method.
public void setupGUI() {
UI.addButton("Load", () -> loadNetworkWithCoordinates(UIFileChooser.open()));
UI.addButton("Print Network", this::printNetwork);
UI.addTextField("Reachable from", this::printReachable);
UI.addButton("All Connected Groups", this::printConnectedGroups);
UI.addButton("Clear", () -> { UI.clearText(); UI.clearGraphics(); });
UI.addButton("Quit", UI::quit);
UI.setWindowSize(800, 600);
UI.setDivider(1.0);
// Load initial network if desired
// loadNetworkWithCoordinates("data-with-lat-long.txt");
// Add mouse listener
UI.setMouseListener(this::handleMouse);
// Initial draw
drawNetwork();
}
handleMouse Method
public void handleMouse(String action, double x, double y) {
if (action.equals("released")) { // On mouse release
Town clickedTown = null;
for (Town town : busNetwork.values()) {
if (town.containsPoint(x, y)) {
clickedTown = town;
break;
}
}
if (clickedTown != null) {
UI.println("Clicked on town: " + clickedTown.getName());
highlightConnectedNetwork(clickedTown);
}
}
}
highlightConnectedNetwork Method
public void highlightConnectedNetwork(Town town) {
if (town == null) return;
Set<Town> connected = findAllConnected(town);
UI.clearGraphics();
UI.setColor(Color.LIGHT_GRAY);
UI.setLineWidth(2);
// Redraw connections, highlighting those in the connected set
for (Town t : busNetwork.values()) {
for (Town neighbor : t.getNeighbours()) {
if (t.getName().compareTo(neighbor.getName()) < 0) {
if (connected.contains(t) && connected.contains(neighbor)) {
UI.setColor(Color.RED);
UI.setLineWidth(3);
} else {
UI.setColor(Color.LIGHT_GRAY);
UI.setLineWidth(2);
}
UI.drawLine(t.getX(), t.getY(), neighbor.getX(), neighbor.getY());
}
}
}
// Redraw towns, highlighting those in the connected set
for (Town t : busNetwork.values()) {
if (connected.contains(t)) {
UI.setColor(Color.ORANGE);
UI.fillOval(t.getX() - 7, t.getY() - 7, 14, 14);
UI.setColor(Color.BLACK);
UI.drawOval(t.getX() - 5, t.getY() - 5, 10, 10);
UI.drawString(t.getName(), t.getX() + 5, t.getY() - 5);
} else {
UI.setColor(Color.BLUE);
UI.fillOval(t.getX() - 5, t.getY() - 5, 10, 10);
UI.setColor(Color.BLACK);
UI.drawString(t.getName(), t.getX() + 5, t.getY() - 5);
}
}
}
Explanation:
- Mouse Listener: When the user releases the mouse button, the
handleMouse method checks if the click was on any town.
- Highlighting:
- Connections: Lines between connected towns are redrawn. If both towns are in the connected set, the line is highlighted in red and made thicker.
- Towns: Towns in the connected set are drawn with a larger orange circle to indicate selection, while others remain blue.
5. Final Adjustments and Enhancements
To make the graphical interface more robust and user-friendly, consider the following enhancements:
a. Zoom and Pan
Implement zooming and panning capabilities to navigate large networks.
b. Tooltips
Display additional information (e.g., town coordinates) when hovering over a town.
c. Dynamic Loading
Allow dynamic loading and switching between different network files without restarting the application.
d. Improved Aesthetics
Enhance the visual presentation with better colors, fonts, and scaling.
e. Error Handling
Add comprehensive error handling to manage edge cases, such as overlapping towns or invalid data.
Complete Updated BusNetworks Class
Combining all the above steps, here's the complete updated BusNetworks class with graphical display and interactivity:
import ecs100.*;
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.awt.Color;
public class BusNetworks {
/** Map of towns, indexed by their names */
private Map<String, Town> busNetwork = new HashMap<String, Town>();
/** Loads a network of towns with coordinates from a file */
public void loadNetworkWithCoordinates(String filename) {
try {
busNetwork.clear();
UI.clearGraphics(); // Clear any previous drawings
UI.clearText();
List<String> lines = Files.readAllLines(Path.of(filename));
if (lines.isEmpty()) {
UI.println("Empty file.");
return;
}
int numberOfTowns = Integer.parseInt(lines.remove(0).trim());
// Read each town's name and coordinates
for (int i = 0; i < numberOfTowns; i++) {
if (lines.isEmpty()) {
UI.println("Not enough town entries.");
return;
}
String line = lines.remove(0).trim();
String[] parts = line.split("\\s+");
if (parts.length >= 3) {
String name = parts[0];
double latitude = Double.parseDouble(parts[1]);
double longitude = Double.parseDouble(parts[2]);
if (!busNetwork.containsKey(name)) {
Town town = new Town(name, latitude, longitude);
busNetwork.put(name, town);
} else {
UI.println("Duplicate town name found: " + name);
}
} else {
UI.println("Invalid town entry: " + line);
}
}
// Read the connections
for (String line : lines) {
String[] connection = line.split("\\s+");
if (connection.length == 2) {
String town1 = connection[0];
String town2 = connection[1];
Town townObj1 = busNetwork.get(town1);
Town townObj2 = busNetwork.get(town2);
if (townObj1 != null && townObj2 != null) {
townObj1.addNeighbour(townObj2);
townObj2.addNeighbour(townObj1);
} else {
UI.println("Invalid connection: " + town1 + " - " + town2);
}
} else {
UI.println("Invalid connection line: " + line);
}
}
UI.println("Loaded " + busNetwork.size() + " towns with coordinates.");
drawNetwork(); // Initial draw
} catch (IOException e) {
throw new RuntimeException("Loading " + filename + " failed: " + e);
} catch (NumberFormatException e) {
UI.println("Invalid number format: " + e.getMessage());
}
}
/** Print all the towns and their neighbours */
public void printNetwork() {
UI.println("The current network: \n====================");
List<Town> sortedTowns = new ArrayList<>(busNetwork.values());
sortedTowns.sort(Comparator.comparing(Town::getName));
for (Town town : sortedTowns) {
StringBuilder sb = new StringBuilder(town.getName() + " -> ");
List<Town> sortedNeighbors = new ArrayList<>(town.getNeighbours());
sortedNeighbors.sort(Comparator.comparing(Town::getName));
for (Town neighbor : sortedNeighbors) {
sb.append(neighbor.getName()).append(" ");
}
UI.println(sb.toString().trim());
}
}
/** Return a set of all the nodes that are connected to the given node */
public Set<Town> findAllConnected(Town town) {
if (town == null) return Collections.emptySet();
Set<Town> visited = new HashSet<>();
recurseTraverse(visited, town);
return visited;
}
public void recurseTraverse(Set<Town> visited, Town current) {
if (visited.contains(current)) return;
visited.add(current);
for (Town neighbor : current.getNeighbours()) {
recurseTraverse(visited, neighbor);
}
}
/** Print all reachable towns from the given town */
public void printReachable(String name){
Town town = busNetwork.get(name);
if (town == null){
UI.println(name+" is not a recognised town");
}
else {
UI.println("\nFrom "+town.getName()+" you can get to:");
Set<Town> reachable = findAllConnected(town);
reachable.remove(town); // Exclude the town itself
List<Town> sortedReachable = new ArrayList<>(reachable);
sortedReachable.sort(Comparator.comparing(Town::getName));
for (Town t : sortedReachable) {
UI.println(t.getName());
}
}
}
/** Print all connected groups of towns */
public void printConnectedGroups() {
UI.println("Groups of Connected Towns: \n================");
int groupNum = 1;
Set<Town> visitedTowns = new HashSet<>();
List<Town> sortedTowns = new ArrayList<>(busNetwork.values());
sortedTowns.sort(Comparator.comparing(Town::getName));
for (Town town : sortedTowns) {
if (!visitedTowns.contains(town)) {
Set<Town> connectedTowns = findAllConnected(town);
UI.print("\nGroup " + groupNum + ": ");
List<Town> sortedGroup = new ArrayList<>(connectedTowns);
sortedGroup.sort(Comparator.comparing(Town::getName));
for (Town t : sortedGroup) {
UI.print(t.getName() + " ");
}
visitedTowns.addAll(connectedTowns);
groupNum++;
}
}
}
/** Draw the network graphically */
public void drawNetwork() {
UI.clearGraphics();
UI.setColor(Color.BLACK);
UI.setLineWidth(1);
if (busNetwork.isEmpty()) {
UI.println("No towns to display.");
return;
}
// Find min and max for scaling
double minLat = Double.MAX_VALUE, maxLat = -Double.MAX_VALUE;
double minLong = Double.MAX_VALUE, maxLong = -Double.MAX_VALUE;
for (Town town : busNetwork.values()) {
if (town.getLatitude() < minLat) minLat = town.getLatitude();
if (town.getLatitude() > maxLat) maxLat = town.getLatitude();
if (town.getLongitude() < minLong) minLong = town.getLongitude();
if (town.getLongitude() > maxLong) maxLong = town.getLongitude();
}
// Define padding and scaling
double padding = 50;
double windowWidth = 800 - 2 * padding;
double windowHeight = 600 - 2 * padding;
double latRange = maxLat - minLat;
double longRange = maxLong - minLong;
// Compute GUI positions for each town
for (Town town : busNetwork.values()) {
double x = padding + ((town.getLongitude() - minLong) / longRange) * windowWidth;
double y = padding + ((maxLat - town.getLatitude()) / latRange) * windowHeight; // Invert y-axis
town.setGUIPosition(x, y);
}
// Draw connections
UI.setColor(Color.LIGHT_GRAY);
UI.setLineWidth(2);
for (Town town : busNetwork.values()) {
for (Town neighbor : town.getNeighbours()) {
if (town.getName().compareTo(neighbor.getName()) < 0) { // Avoid duplicates
UI.drawLine(town.getX(), town.getY(), neighbor.getX(), neighbor.getY());
}
}
}
// Draw towns
for (Town town : busNetwork.values()) {
UI.setColor(Color.BLUE);
UI.fillOval(town.getX() - 5, town.getY() - 5, 10, 10);
UI.setColor(Color.BLACK);
UI.drawString(town.getName(), town.getX() + 5, town.getY() - 5);
}
}
/** Handle mouse clicks */
public void handleMouse(String action, double x, double y) {
if (action.equals("released")) { // On mouse release
Town clickedTown = null;
for (Town town : busNetwork.values()) {
if (town.containsPoint(x, y)) {
clickedTown = town;
break;
}
}
if (clickedTown != null) {
UI.println("Clicked on town: " + clickedTown.getName());
highlightConnectedNetwork(clickedTown);
}
}
}
/** Highlight the connected network of the clicked town */
public void highlightConnectedNetwork(Town town) {
if (town == null) return;
Set<Town> connected = findAllConnected(town);
if (connected.isEmpty()) return;
UI.clearGraphics();
UI.setLineWidth(2);
// Redraw connections with highlights
for (Town t : busNetwork.values()) {
for (Town neighbor : t.getNeighbours()) {
if (t.getName().compareTo(neighbor.getName()) < 0) {
if (connected.contains(t) && connected.contains(neighbor)) {
UI.setColor(Color.RED);
UI.setLineWidth(3);
} else {
UI.setColor(Color.LIGHT_GRAY);
UI.setLineWidth(1);
}
UI.drawLine(t.getX(), t.getY(), neighbor.getX(), neighbor.getY());
}
}
}
// Redraw towns with highlights
for (Town t : busNetwork.values()) {
if (connected.contains(t)) {
UI.setColor(Color.ORANGE);
UI.fillOval(t.getX() - 7, t.getY() - 7, 14, 14);
UI.setColor(Color.BLACK);
UI.drawOval(t.getX() - 5, t.getY() - 5, 10, 10);
UI.drawString(t.getName(), t.getX() + 5, t.getY() - 5);
} else {
UI.setColor(Color.BLUE);
UI.fillOval(t.getX() - 5, t.getY() - 5, 10, 10);
UI.setColor(Color.BLACK);
UI.drawString(t.getName(), t.getX() + 5, t.getY() - 5);
}
}
}
/** Set up the GUI */
public void setupGUI() {
UI.addButton("Load", () -> loadNetworkWithCoordinates(UIFileChooser.open()));
UI.addButton("Print Network", this::printNetwork);
UI.addTextField("Reachable from", this::printReachable);
UI.addButton("All Connected Groups", this::printConnectedGroups);
UI.addButton("Clear", () -> { UI.clearText(); UI.clearGraphics(); });
UI.addButton("Quit", UI::quit);
UI.setWindowSize(800, 600);
UI.setDivider(1.0);
// Optionally load an initial network
// loadNetworkWithCoordinates("data-with-lat-long.txt");
// Add mouse listener
UI.setMouseListener(this::handleMouse);
// Initial draw
drawNetwork();
}
// Main
public static void main(String[] arguments) {
BusNetworks bnw = new BusNetworks();
bnw.setupGUI();
}
}
Town Class (Complete Version)
import java.util.*;
public class Town {
private String name;
private double latitude;
private double longitude;
private Set<Town> neighbours;
// GUI coordinates (computed based on latitude and longitude)
private double x;
private double y;
private static final double RADIUS = 10; // Radius for detecting clicks
public Town(String name, double latitude, double longitude) {
this.name = name;
this.latitude = latitude;
this.longitude = longitude;
this.neighbours = new HashSet<>();
}
public String getName() {
return name;
}
public Set<Town> getNeighbours() {
return neighbours;
}
public void addNeighbour(Town town) {
neighbours.add(town);
}
// Getters for coordinates
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
// Getters and setters for GUI positions
public double getX() {
return x;
}
public double getY() {
return y;
}
public void setGUIPosition(double x, double y) {
this.x = x;
this.y = y;
}
// Method to check if a point is within the town's circle
public boolean containsPoint(double px, double py) {
double dx = px - x;
double dy = py - y;
return dx * dx + dy * dy <= RADIUS * RADIUS;
}
@Override
public String toString() {
return name;
}
}
Testing the Application
-
Prepare the Data File: Ensure you have a data-with-lat-long.txt file formatted as described earlier.
Example data-with-lat-long.txt:
5
TownA 34.05 -118.25
TownB 36.12 -115.17
TownC 40.71 -74.00
TownD 34.05 -117.29
TownE 37.77 -122.42
TownA TownB
TownB TownC
TownC TownD
TownD TownE
-
Run the Application: Execute the BusNetworks application. Use the "Load" button to load your data-with-lat-long.txt file.
-
Interact with the Network:
- Click on a town to highlight its connected network.
- Use the "Print Network" and other buttons to view textual information.
- Use "Clear" to reset the display.
-
Verify Functionality: Ensure that clicking on different towns correctly highlights their connected networks and that the graphical representation matches the data.
Additional Considerations
-
Handling Overlapping Towns: In cases where multiple towns have similar or identical coordinates, consider implementing clustering or slight randomization to prevent overlapping visuals.
-
Dynamic Scaling: Adjust the zoom level based on the density of towns to maintain clarity.
-
Performance Optimization: For very large networks, optimize the drawing methods to maintain responsiveness.
-
User Feedback: Provide visual feedback (e.g., cursor changes) when hovering over interactive elements like towns.
-
Extensibility: Design the application to support additional features, such as searching for specific paths or integrating real map data.
By following the above steps and utilizing the provided code, you can create a comprehensive graphical representation of the bus network, enhancing both the functionality and user experience of your BusNetworks application. This setup provides a solid foundation, allowing for further enhancements and scalability based on your project requirements.