Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Contents

I. Introduction...................................................................................................................................2
II. Project Overview...........................................................................................................................2
III. Project Structure.......................................................................................................................2
IV. Execution...................................................................................................................................3
1. Import the Project:...................................................................................................................3
2. Configure Build Path:..............................................................................................................3
3. Run the Main Class:.................................................................................................................3
4. Execution:..................................................................................................................................3
5. Interacting with the Application:............................................................................................3
6. Exit the Application:.................................................................................................................4
V. Code Explanation..........................................................................................................................4
1. PolyShapes.java........................................................................................................................4
2. PolyShapesController.java.......................................................................................................5
3. PolyShapes.fxml........................................................................................................................8
4. PolyShapes.css.........................................................................................................................11
VI. Conclusion...............................................................................................................................12

I. Introduction
This report presents a detailed overview of a JavaFX project aimed at creating an
interactive shape drawing application. The project leverages JavaFX technology to
develop a user-friendly graphical interface for drawing various shapes such as polylines,
polygons, and paths. This report delves into the design, implementation, challenges faced,
solutions devised, testing procedures, and future enhancements of the application.
II. Project Overview
The JavaFX application facilitates the creation of shapes through intuitive mouse-click
interactions. Users can draw different shapes on a canvas, manipulate their properties, and
clear the canvas as needed. The project's objective is to provide a versatile and engaging
platform for users to experiment with basic shapes and understand the principles of
graphical programming.
III. Project Structure
The Project contain four main files.
 PolyShapes.java
 PolyShapesController.java
 PolyShapes.css
 PolyShapes.fxml
These files are implemented in the following format.
1. src/main/java/com/example/shapes:
 PolyShapes.java: Main class for the JavaFX application.
 PolyShapesController.java: Controller class for managing GUI interactions.
2. src/main/resources/com/example/shapes:
 PolyShapes.css: CSS file for styling the GUI components.
 PolyShapes.fxml: FXML file defining the layout of the GUI.
This structure organizes the source code files and resources necessary for the JavaFX
project under appropriate packages and directories. It separates the Java code from the
resources, making the project easy to navigate and manage.

IV.Execution
1. Import the Project:
 Open Eclipse IDE.
 Select File > Import from the top menu.
 Choose Existing Projects into Workspace under the General category.
 Click Next.
 Browse to the directory where your JavaFX project is located.
 Select the project folder (PolyShapes) and click Finish.
2. Configure Build Path:
 Right-click on the project in the Package Explorer.
 Select Build Path > Configure Build Path.
 Navigate to the Libraries tab.
 Add the JavaFX library to the build path:
 Click Add Library.
 Choose User Library and click Next.
 Click User Libraries....
 Click New and give the library a name (e.g., JavaFX).
 Add the JavaFX JAR files (e.g., javafx.base, javafx.controls,
javafx.fxml, javafx.graphics) to the library.
 Click OK, then Finish, and finally Apply and Close.
3. Run the Main Class:
 Open the PolyShapes.java file.
 Right-click on the file in the editor or Package Explorer.
 Select Run As > Java Application.
4. Execution:
 Upon running the program, the JavaFX application window titled "Draw
Polylines, Polygons, and Paths" should appear.
 Use the radio buttons to select the type of shape you want to draw (Polyline,
Polygon, or Path).
 Click on the drawing area to create points and form the desired shape.
 You can switch between different shape types by selecting the corresponding
radio button.
 Use the "Clear" button to reset the canvas and remove all drawn shapes.
5. Interacting with the Application:
 Interact with the application by clicking on the drawing area to draw shapes.
 Explore different functionalities such as drawing polylines, polygons, and
paths.
 Test the application's responsiveness and behavior by switching between shape
types and clearing the canvas.
6. Exit the Application:
 Close the application window when you're finished testing or exploring the
functionalities.
V. Code Explanation
1. PolyShapes.java
package com.example.shapes;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class PolyShapes extends Application {


@Override
public void start(Stage stage) throws Exception {
Parent root =
FXMLLoader.load(getClass().getResource("PolyShapes.fxml"));

Scene scene = new Scene(root);


stage.setTitle("Draw Polylines, Polygons and Paths");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);
}
}

a) Package Declaration (package com.example.shapes;):


 Specifies the package in which the PolyShapes class is located. Packages help
organize classes into logical groups.
b) Import Statements:
 Import necessary JavaFX classes for creating GUI components, scenes, and
stages.
c) Class Declaration (public class PolyShapes extends Application {):
 Defines the PolyShapes class, which extends the Application class provided
by JavaFX. This means that PolyShapes is a JavaFX application and can be
launched using the JavaFX runtime environment.
d) start() Method Override:
 Overrides the start() method from the Application class. The start() method
is the entry point for JavaFX applications.
e) FXMLLoader:
 Loads the FXML layout file (PolyShapes.fxml) and generates the
corresponding GUI components specified in the FXML markup.
f) Scene Creation:
 Creates a new scene and sets the root node to the loaded FXML layout (root).
The scene represents the content of the JavaFX application window.
g) Stage Configuration:
 Configures the stage (main window) of the JavaFX application. Sets the title
of the stage to "Draw Polylines, Polygons, and Paths" and sets the scene to the
one created earlier.
h) main() Method:
 The main entry point of the JavaFX application. Calls the launch() method
inherited from the Application class to launch the JavaFX application.

2. PolyShapesController.java

package com.example.shapes;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.ArcTo;
import javafx.scene.shape.ClosePath;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Polyline;

public class PolyShapesController {


private enum ShapeType {POLYLINE, POLYGON, PATH};

@FXML private RadioButton polylineRadioButton;


@FXML private RadioButton polygonRadioButton;
@FXML private RadioButton pathRadioButton;
@FXML private ToggleGroup toggleGroup;
@FXML private Polyline polyline;
@FXML private Polygon polygon;
@FXML private Path path;

private ShapeType shapeType = ShapeType.POLYLINE;


private boolean sweepFlag = true;

public void initialize() {


polylineRadioButton.setUserData(ShapeType.POLYLINE);
polygonRadioButton.setUserData(ShapeType.POLYGON);
pathRadioButton.setUserData(ShapeType.PATH);

displayShape();
}

@FXML
private void drawingAreaMouseClicked(MouseEvent e) {
polyline.getPoints().addAll(e.getX(), e.getY());
polygon.getPoints().addAll(e.getX(), e.getY());

if (path.getElements().isEmpty()) {
path.getElements().add(new MoveTo(e.getX(), e.getY()));
path.getElements().add(new ClosePath());
}
else {
ArcTo arcTo = new ArcTo();
arcTo.setX(e.getX());
arcTo.setY(e.getY());
arcTo.setRadiusX(100.0);
arcTo.setRadiusY(100.0);
arcTo.setSweepFlag(sweepFlag);
sweepFlag = !sweepFlag;
path.getElements().add(path.getElements().size() - 1, arcTo);
}
}
@FXML
private void shapeRadioButtonSelected(ActionEvent e) {
shapeType =
(ShapeType) toggleGroup.getSelectedToggle().getUserData();
displayShape();
}

private void displayShape() {


polyline.setVisible(shapeType == ShapeType.POLYLINE);
polygon.setVisible(shapeType == ShapeType.POLYGON);
path.setVisible(shapeType == ShapeType.PATH);
}

@FXML
private void clearButtonPressed(ActionEvent event) {
polyline.getPoints().clear();
polygon.getPoints().clear();
path.getElements().clear();
}
}

a) Package Declaration:
 Specifies the package in which the PolyShapesController class is located
(package com.example.shapes;).
 Packages in Java serve to organize related classes into logical groups,
facilitating code organization, readability, and maintenance.
 The specified package name (com.example.shapes) follows the convention of
reverse domain naming to ensure uniqueness and avoid naming conflicts.
b) Import Statements:
 Import necessary JavaFX classes for handling GUI events and shapes.
 Import statements allow access to classes and packages defined in other
packages or libraries.
 In this context, JavaFX classes are imported to enable the use of GUI
components and event handling functionalities within the
PolyShapesController class.
c) Class Declaration:
 Defines the PolyShapesController class responsible for managing the
behavior of GUI components defined in the FXML file (public class
PolyShapesController {).
 The class declaration includes the access modifier (public) indicating that the
class is accessible from other classes, and the class name
(PolyShapesController) following the camelCase naming convention.
d) FXML Annotations:
 Annotations (@FXML) are used to inject GUI components defined in the
FXML file into the controller class.
 Annotating instance variables and methods with @FXML allows JavaFX to
establish a connection between the controller class and the corresponding
elements defined in the FXML file.
 This enables event handling and interaction with GUI components from within
the controller class.
e) Enum Declaration:
 Defines an enumeration representing the types of shapes that can be drawn
(private enum ShapeType {POLYLINE, POLYGON, PATH};).
 Enumerations provide a way to represent a fixed set of constants, making the
code more readable and maintainable.
 In this case, the ShapeType enum defines three constants representing
different types of shapes: POLYLINE, POLYGON, and PATH.
f) Instance Variables:
 Declare instance variables for GUI components (RadioButton, ToggleGroup,
Polyline, Polygon, Path) and other necessary variables.
 Instance variables are declared to hold references to GUI components such as
radio buttons, shapes, and toggle groups.
 These variables are annotated with @FXML to enable JavaFX to inject them
with instances of corresponding elements defined in the FXML file.
g) initialize() Method:
 An initialization method annotated with @FXML. It is called when the FXML
file is loaded and sets up the initial state of GUI components.
 The initialize() method serves as a callback method invoked by JavaFX after
the FXML file has been loaded and all @FXML-annotated fields have been
injected.
 It is commonly used to perform additional setup tasks or initialize the state of
GUI components.
h) Event Handlers:
 Methods annotated with @FXML that handle user interactions such as mouse
clicks, radio button selections, and button presses
(drawingAreaMouseClicked(),shapeRadioButtonSelected(),
clearButtonPressed()).
 Event handler methods are triggered in response to user interactions with GUI
components, such as clicking a mouse button or selecting a radio button.
 These methods are annotated with @FXML to indicate to JavaFX that they
are event handlers for specific GUI components defined in the FXML file.
i) displayShape() Method:
 Controls the visibility of different shapes based on the selected radio button.
 The displayShape() method is responsible for showing or hiding different
shapes (polyline, polygon, path) based on the selected radio button.
 It ensures that only the relevant shape is displayed on the canvas area,
providing a seamless user experience.

3. PolyShapes.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.TitledPane?>
<?import javafx.scene.control.ToggleGroup?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.shape.Path?>
<?import javafx.scene.shape.Polygon?>
<?import javafx.scene.shape.Polyline?>

<BorderPane prefHeight="200.0" prefWidth="400.0" stylesheets="@PolyShapes.css"


xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="com.example.shapes.PolyShapesController">
<left>
<VBox prefHeight="200.0" prefWidth="100.0" spacing="8.0"
BorderPane.alignment="CENTER">
<children>
<TitledPane text="Select Type">
<content>
<VBox spacing="8.0">
<children>
<RadioButton fx:id="polylineRadioButton"
mnemonicParsing="false" onAction="#shapeRadioButtonSelected" selected="true"
text="Polyline">
<toggleGroup>
<ToggleGroup fx:id="toggleGroup" />
</toggleGroup></RadioButton>
<RadioButton fx:id="polygonRadioButton"
mnemonicParsing="false" onAction="#shapeRadioButtonSelected" text="Polygon"
toggleGroup="$toggleGroup" />
<RadioButton fx:id="pathRadioButton" mnemonicParsing="false"
onAction="#shapeRadioButtonSelected" text="Path" toggleGroup="$toggleGroup" />
</children>
</VBox>
</content>
</TitledPane>
<Button fx:id="clearButton" maxWidth="1.7976931348623157E308"
mnemonicParsing="false" onAction="#clearButtonPressed" text="Clear" />
</children>
</VBox>
</left>
<padding>
<Insets bottom="8.0" left="8.0" right="8.0" top="8.0" />
</padding>
<center>
<Pane onMouseClicked="#drawingAreaMouseClicked" prefHeight="200.0"
prefWidth="200.0" style="-fx-background-color: white;"
BorderPane.alignment="CENTER">
<BorderPane.margin>
<Insets left="8.0" />
</BorderPane.margin>
<children>
<Polyline fx:id="polyline" layoutX="0.0" layoutY="0.0" visible="false"
/>
<Polygon fx:id="polygon" layoutX="0.0" layoutY="0.0" visible="false" />
<Path fx:id="path" layoutX="0.0" layoutY="0.0" visible="false" />
</children>
</Pane>
</center>
</BorderPane>

a) FXML File Declaration:


 Specifies the XML version (1.0) and encoding (UTF-8) used in the FXML file.
 This declaration ensures that the XML parser correctly interprets the file's
content.
b) FXML Namespace Declaration:
 Declares namespaces used within the FXML file, including the JavaFX
namespace (xmlns="http://javafx.com/javafx/8.0.60") and the FXML
namespace (xmlns:fx="http://javafx.com/fxml/1").
 The JavaFX namespace defines the elements and attributes available for
building JavaFX UI components, while the FXML namespace enables the use
of FXML-specific features and attributes.
c) FXML Root Element:
 Defines the root element of the FXML file, which is a BorderPane.
 The BorderPane layout divides the window into five regions: top, right,
bottom, left, and center. In this case, the left and center regions are utilized for
organizing the controls and drawing area, respectively.
d) VBox for Controls:
 Contains the controls for selecting shape types and clearing the canvas.
 The VBox layout arranges the controls vertically, ensuring a compact and
organized presentation.
 The controls are placed within a titled pane (TitledPane) to provide a visual
grouping and to improve the clarity of the user interface.
e) Radio Buttons:
 Provide options for selecting different shape types: polyline, polygon, and
path.
 Radio buttons allow the user to choose a single shape type at a time, ensuring
mutually exclusive selection.
 Each radio button is associated with the toggleGroup, which ensures that only
one radio button can be selected within the group.
f) Clear Button:
 Allows clearing the canvas area of drawn shapes.
 The clear button provides a convenient way for the user to reset the canvas,
removing any existing shapes and allowing for a fresh drawing session.
g) Pane for Drawing Area:
 Contains the canvas area where shapes are drawn.
 The Pane serves as a flexible container for displaying graphical elements,
providing a blank canvas for drawing shapes.
 It can accommodate various shapes, such as polylines, polygons, and paths,
based on user input and interaction.
h) Mouse Click Event Handler:
 Defines the onMouseClicked attribute to handle mouse click events on the
drawing area.
 Mouse click events trigger the associated event handler
(drawingAreaMouseClicked()) in the controller class, enabling interactive
drawing functionality.
i) Shape Elements:
 Includes placeholders for displaying polylines, polygons, and paths.
 These elements are initially hidden (visible="false") and will be made visible
dynamically based on the user's selection of shape type.
 Each shape element (polyline, polygon, path) represents a drawable entity on
the canvas, allowing for the creation of different geometric shapes.
j) Padding:
 Specifies padding for the root BorderPane element, ensuring some space between the
edges of the window and the contained elements.
 Padding improves the visual appearance of the layout and enhances readability by
providing adequate spacing around UI components.

4. PolyShapes.css
Polyline, Polygon, Path {
-fx-stroke: black;
-fx-stroke-width: 5;
-fx-fill: red;
}
 Cascading Style Sheet (CSS) file responsible for defining the visual presentation of
graphical elements in the JavaFX application.
 CSS rules specified in this file target specific JavaFX shape elements, including
polyline, polygon, and path.
 -fx-stroke property sets the color of the stroke (outline) of the shapes to black,
ensuring clear visibility against the canvas background.
 -fx-stroke-width property defines the width of the stroke, ensuring consistent line
thickness for the drawn shapes.
 -fx-fill property sets the fill color of the shapes to red, providing a distinct color for
the interior of the shapes.
 Separation of styling concerns into a separate CSS file promotes modularity and
maintainability, enabling easy customization of the visual appearance without altering
the Java code.
VI. Conclusion
In conclusion, this document has provided a comprehensive overview of the JavaFX project
aimed at creating an interactive shape drawing application. Through detailed explanations of
the PolyShapes.java, PolyShapesController.java, PolyShapes.fxml, and associated CSS
files, we have gained insights into the design, implementation, and functionality of the
application. (JavaFX Documentation, n.d.)
The PolyShapes.java file serves as the main entry point of the application, leveraging
JavaFX technology to initialize the graphical user interface and handle user interactions. With
the PolyShapesController.java file, the application's behavior is managed, including event
handling, shape drawing logic, and UI component initialization. The FXML file,
PolyShapes.fxml, defines the layout and structure of the application's user interface,
providing a visual representation of the controls and drawing area.
Throughout the document, detailed explanations have been provided for each component,
including package declarations, import statements, class declarations, event handlers, and
GUI components. Additionally, the document has highlighted the significance of annotations,
enums, and instance variables in facilitating the application's functionality.
References
Deitel, P. (2017). Java How to Program, 11th Edition. Pearson.
Getting Started with JavaFX. (n.d.). Retrieved from Oracle:
https://docs.oracle.com/javafx/2/get_started/jfxpub-get_started.htm
JavaFX Documentation. (n.d.). Retrieved from oracle:
https://www.oracle.com/java/technologies/javase/javafx-docs.html
JavaFX, G. S. (2018). Mastering JavaFX 10. Packt Publishing Ltd.
Questions tagged [javafx]. (n.d.). Retrieved from stackoverflow:
https://stackoverflow.com/questions/tagged/JavaFX

You might also like