---
# System prepended metadata

title: Computer Programming II Pre-Lab 11
tags: [Computer Engineering, IUG, Computer Programming II, Pre-Lab]

---

---
title: Computer Programming II Pre-Lab 11
---
<h1 style='border: none'><center>Computer Programming II Pre-Lab 11</center></h1>
<h2 style='border: none'><center>JavaFX Table View & Media Elements & Animations</center></h2>
<h5><center>The Islamic University of Gaza<br>Engineering Faculty<br>Department of Computer Engineering</center></h5>
<h6>Authors: Usama R. Al Zayan<span style="float:right">2023/05/19</span></h6>
<h6>Parts of this Lab were adapted from work done by Mohammed Nafiz ALMadhoun and  Mohammed AlBanna</h6>
---

---



<p style='text-align:justify'>
In this lab, we are going to explore some components in JavaFX, we will first talk about media elements, and how we could play a video, or music in JavaFX, and then we will talk about Table Views, which will enable us to show tabular data, finally we will talk about how to create animations in JavaFX, this will not only allow you to create simple animations but to do updates in certain intervals and more.
</p>

# Media Elements

The media elements in JavaFX are pretty straightforward, you will add the element, then you will set the path for the element to play and that's it!

<center>

![Media View Example](https://i.imgur.com/moaa9I4.png =400x)
Media View Example
</center>

### Media Class

The media class will define the media source for the elements, so it will contain the path of the media.

```java=
Media media = new Media("File URI");
```

Notice that you could get the file URI from a resource, or use the `File` class.

The media element doesn't play anything on its own, it will just define the resource and a helper for reading the file.

### Media Player

The media player class will allow us to play and control a media file, notice that this will control it but never view it, so it is the player, not the viewer.

```java=
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
```

Try to create a media player to play something, you will notice that the sound will stop after 5 seconds or so, this is due to the garbage collector deleting our media player, so be sure to define it somewhere safe!

### Media View

The media view element is responsible for showing the media (e.g video), this is a regular component you can add anywhere you want and it will show the video for you!

```java=
Media media = new Media("file:///D:/TA/Programming/Portal2.mp4");
MediaPlayer mediaPlayer = new MediaPlayer(media);
MediaView mediaView = new MediaView(mediaPlayer);
mediaPlayer.play();
```

You could now create your control elements to control the media player!

# Table View

The table view is a very common and useful component, Table view will allow you to view data as a table, sort data, edit data, and more.
<center>

![Table View Example](https://i.imgur.com/nFVjKwb.png =400x)
Table View Example
</center>

The table view is a generic class, which takes the type of each row in it, which makes it easier for the developer to work with.

```java=
TableView<Student> table = new TableView<Student>();
table.getItems().add(new Student("Mohammed", 25));
```

Now, let create a colume for the data we want to view.
```java=
TableColumn<Student, String> nameColumn = new TableColumn<>("Name");
table.getColumns().add(nameColumn);
```

Notice that the column will not show the data, we should define for the column how to get the value of `Name` from `Student` class.

We could do that by extending `CellDataFeatures`, or we could easily use `PropertyValueFactory`, which will try to get an observable property or use the `get` method to get the data.

```java=
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
```

### Cell Factory

You could change how the cell gets viewed, for example, you could display a checkbox instead of the string `true`, `false`, or you could create a combo box.

```java=
TableColumn<Student, Boolean> testColumn = new TableColumn<>("Test");
testColumn.setCellValueFactory(new PropertyValueFactory<>("test"));
testColumn.setCellFactory(CheckBoxTableCell.forTableColumn(testColumn));
```

You could use `TextFieldTableCell`, which will allow you to show a text field to edit string data or use `ComboBoxTableCell` to create a combo box.

### Editable Table View

You could make the table view editable using the method `setEditable`, which will allow the user to edit the values.

If you used a `Property`, the table view will know how to handle edits, but if used regular classes, you will have to handle it yourself.

```java=
TableColumn<Student, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nameColumn.setOnEditCommit(cellEditEvent -> {
    cellEditEvent.getRowValue().setName(cellEditEvent.getNewValue());
});
```

Notice that because we're using generics, we get the row as the type of the data `Student`.

So use `StringProperty` to make your life easier!

### Selection Model

The table selection model is responsible for the selection of rows, you can get the selected row like this:
```java=
table.getSelectionModel().getSelectedItem()
```

You could enable multipale selection like this:
```java=
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
```

# Animation Class

The animation class is an abstract class that defines common things for all animations, for example:
* Play
* Pause
* Cycle Count
* Auto Reverse

To create an animation, we will use one of the following classes.

### Path Transition Class

As the name indicates that the class create an animation that moves something over a path, so let's create a path and animate something over it.

#### Creating a polyline 
```java=
Polyline polyline = new Polyline(0,0, 10,10, 100,0, 200,200, 300,200, 400,400);
```
Notice that polyline takes an array of doubles, each two values indicate a point (x, y).

<center>

![Polyline Output](https://i.imgur.com/LrTiBGZ.png =300x)
Polyline Output
</center>

#### Creating a circle

We will move a circle over the polyline, so we will create a circle shape.

```java=
Circle circle = new Circle(10);
```

#### Creating Path Transition

```java=
Duration duration = new Duration(3000);
PathTransition pathTransition = new PathTransition(duration, polyline, circle);
pathTransition.setAutoReverse(true);
pathTransition.setCycleCount(Timeline.INDEFINITE);
pathTransition.play();
```

now by adding the polyline and circle to a Pane, we could run our scene.

```java=
Pane pane = new Pane(polyline, circle);
```
<center>

![Path Transition Example](https://i.imgur.com/EyWWdAl.png =300x)
Path Transition Example
</center>


### Fade Transition Class

This class will allow us to control the opacity of an object, in this example, we will create a button that fades in when the mouse entered over it and fades out when it exited.

```java=
Button btn = new Button("Test");
FadeTransition fadeTransition = new FadeTransition(new Duration(200), btn);
btn.setOpacity(0.4);
btn.setOnMouseEntered(e -> {
    fadeTransition.stop();
    fadeTransition.setFromValue(0.4);
    fadeTransition.setToValue(1);
    fadeTransition.play();
});
btn.setOnMouseExited(e -> {
    fadeTransition.stop();
    fadeTransition.setFromValue(1);
    fadeTransition.setToValue(0.4);
    fadeTransition.play();
});
```
<center>

![Fade transition Example](https://i.imgur.com/ewrPxQv.png =300x)
Fade transition Example
</center>


### Timeline Class

The Timeline class allows you to create anything you like, you will create a KeyFrame (which is a frame with a time), and add all the keyframes to a Timeline which extends the Animation class.

The KeyFrame will take the duration of the frame, onFinish handler, and KeyValues.

In the following example, we will create a bouncing ball, we will first create a ball class:

```java=
class Ball extends Circle {
    Region parent;
    double radius = 0;
    double velocity_y = 0;
    double velocity_x = 0;
    
    public Ball (Region parent, int radius, double velocity_x){
        super(radius);
        this.radius = radius;
        this.parent = parent;
        this.velocity_x = velocity_x;
    }
    public void move (double deltaTime) {
        double currentY = getCenterY();
        if (currentY + radius >= parent.getHeight() && velocity_y > 0) {
            velocity_y *= -0.8;
        }
        velocity_y += 9.8 * deltaTime;
        this.setCenterY(currentY + velocity_y);
        this.setCenterX(this.getCenterX()+ velocity_x);
    }
}
```

Then we will create a Pane to contain all the balls, and animation to run the `move` method.

```java=
ArrayList<Ball> balls = new ArrayList<Ball>();
Pane pane = new Pane();

pane.setOnMousePressed(e -> {
    Ball ball = new Ball(pane, 10, Math.random() - 0.5);
    ball.setCenterX(e.getX());
    ball.setCenterY(e.getY());
    pane.getChildren().add(ball);
    balls.add(ball);
});
Scene scene = new Scene(pane, 640, 480);
KeyFrame keyFrame = new KeyFrame(new Duration (1000/30.0), (event) -> {
    for(Ball ball : balls)
        ball.move(1/30.0);
});
Timeline timeline = new Timeline(keyFrame);
timeline.setCycleCount(-1);
timeline.play();
```


<center>

![Timeline Example](https://i.imgur.com/0kvdcbb.png =300x)
Timeline Example
</center>

Notice that in the KeyFrame finish event, we could write any code we want, the KeyFrame could also contain KeyValues, which will control a certain value.

```java=
Button btn = new Button("Test");
btn.setLayoutX(0);
btn.setLayoutY(0);
Scene scene = new Scene(new Pane(btn), 200, 200);
KeyValue keyValueX = new KeyValue(btn.layoutXProperty(), 200);
KeyValue keyValueY = new KeyValue(btn.layoutYProperty(), 200);
KeyFrame keyFrame = new KeyFrame(new Duration(3000), keyValueX, keyValueY);
Timeline timeline = new Timeline(keyFrame);
timeline.setCycleCount(-1);
timeline.setAutoReverse(true);
timeline.play();
```

# Lab Tasks

## Task 1: Video Player

Create a video player with controls, the video player should have the following:
* Open button: Which let you open a file.
* Pause/Play Button: The button should allow you to pause and play the video.
* Volume bar: This allows you to control the volume.
* Seek bar: This allows you to seek to a certain time.

<center>

![Task 1 Expected Output](https://i.imgur.com/jjXOXrH.png)
Task 1 Expected Output
</center>

**Note:** Don't panic when you implement seek bar XD.


###### tags: `Computer Programming II` `Pre-Lab` `IUG` `Computer Engineering`

<center>End Of Pre-Lab 11</center>