---
# System prepended metadata

title: Computer Programming II Lab 4 v1.0
tags: [Computer Engineering, IUG, Lab, Computer Programming II]

---

---
title: Computer Programming II Lab 4 v1.0
---
<h1 style='border: none'><center>Computer Programming II Lab 4</center></h1>
<h2 style='border: none'><center>More about Inheritance</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/03/04</span></h6>
<h6>Parts of this Lab were adapted from work done by Mohammed Nafiz ALMadhoun</h6>
---

## Lab 4: Time and Plan

| Tasks    | Timing   | 
| -------- | -------- |
| Quiz 1   | 10 min   |
| Task 1   | 60 min   |


<p style='text-align:justify'>
In this lab, we are going to inherit some classes that we didn't create, this should allow us to understand the concept of OOP and how it's very useful in creating many abstraction levels, we will use AWT & Swing libraries as an example.
</p>

**Note:** We won't use AWT or Swing in the next labs, and we won't cover it in the course material.

## Introduction to Swing

Swing is a GUI library for Java, so it will allow you to create GUI applications in Java, note that it's built on top of AWT (Abstract Window Toolkit), notice that later in this course, we will learn to use JavaFX which is a new GUI library for Java.

### Creating a frame

To create a frame (window), we will use `javax.swing.JFrame` class, then we will configure this window and show it.

```java=
import javax.swing.*;

public class Test {
    public static void main (String[] args) {
        JFrame frame = new JFrame("Title");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setVisible(true);
    }
}
```
Configurations:
* Line `6`, we changed the default operation, so when we close the window the whole application will exit.
* Line `7`, we changed the size of this window.
* Line `8`, we set the visibility to true.

<center>

![Figure 1: JFrame](https://i.imgur.com/hMEAsu3.png =300x)
Figure 1: JFrame
</center>


### Adding a component to the frame

You could add a component to the frame using the method `frame.add`, which will take any element of type `java.awt.Component`, for example, we could add `javax.swing.JTextField`.

```java=
...
        JTextField textField = new JTextField();
        textField.setBounds(10, 10, 100, 30);
        frame.add(textField);
        frame.setLayout(null);
        frame.setVisible(true);
...
```
Notice that we changed the layout of the frame to prevent it from stretching the elements.

<center>

![Figure 2: JTextField](https://i.imgur.com/MKueGh1.png =300x)
Figure 2: JTextField
</center>

There is a lot of components that you could use, take a look at this [docs](https://www.javatpoint.com/java-jbutton).

### Extending a component

You could extend the functionality of any component by simply inheriting them, for example, we could create a JTextField that only accept numbers!

This could be achieved easily by overriding `processKeyEvent` method, and checking if this event is a character typing, and if it's a digit:

```java=
import javax.swing.*;
import java.awt.event.KeyEvent;

public class NumbersTextField extends JTextField {
    @Override
    protected void processKeyEvent(KeyEvent e) {
        // This could be written using one if, but here it is for readability
        if (e.getID() != KeyEvent.KEY_TYPED)
            super.processKeyEvent(e);
        else if (Character.isDigit(e.getKeyChar()))
            super.processKeyEvent(e);
    }
}
```

So this text field, will only accept numbers, notice that we've created our new component that could be added to the frame without understanding the whole library!

## AWT Graphics API

In this section, we are going to talk about the AWT Graphics API [find the docs here](https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html), the graphics API will allow you to draw stuff, and it's used by components to draw their shape.

### Extending JPanel Component

The JPanel component is just a lightweight container that has a double buffer, we could extend this component and override its `paintComponent` method.

```java=
class Game extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        
    }
}
```
This will give us access to the graphics API, which we could use to draw anything!

```java=
import javax.swing.*;
import java.awt.Graphics;

public class Test {
    public static void main (String[] args) {
        JFrame frame = new JFrame("Title");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        Game game = new Game();
        frame.add(game);
        frame.setVisible(true);
    }
}

class Game extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        g.fillRect(50, 50, 100, 100);
    }
}
```

<center>

![Figure 3: Extending JPanel](https://i.imgur.com/n89vGdX.png =400x)
Figure 3: Extending JPanel
</center>

Please take a look a the docs to see graphics class methods.

We could override the `` method to move the rect when there is an event!

```java=
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.KeyEvent;

public class Game extends JPanel {
    int boxX = 0;
    int boxY = 0;
    public Game () {
        // This will let use recive keyboard events!
        setFocusable(true);
    }
    @Override
    public void paintComponent(Graphics g) {
        g.clearRect(0, 0, getWidth(), getHeight());
        g.fillRect(boxX,boxY,100,100);
    }
    @Override
    protected void processKeyEvent(KeyEvent e) {
        super.processKeyEvent(e);
        if (e.getID() == KeyEvent.KEY_PRESSED) {
            switch (e.getKeyCode()){
                case KeyEvent.VK_DOWN:
                    boxY++;
                    break;
                case KeyEvent.VK_UP:
                    boxY--;
                    break;
                case KeyEvent.VK_RIGHT:
                    boxX++;
                    break;
                case KeyEvent.VK_LEFT:
                    boxX--;
                    break;  
            }
        }
        // Request a repaint!
        repaint();
    }
}
```

Congratulations you have a moving box!

### Create GameElement Class

We could now create a class name `GameElement`, which has a `draw` method, and `interact` method, these two methods could be overridden, so if we want to create our moving box, we could extend the `GameElement` class.

```java=
public class GameElement {
    public void draw (Graphics g) {
        
    }
    public void interact (KeyEvent e) {
        
    }
}
```

So you could extend this class in many classes, have all your elements as an array, and paint them all together!

```java=
public class Game extends JPanel {
    ...
    GameElement[] elements = ...;
    @Override
    public void paintComponent(Graphics g) {
        g.clearRect(0, 0, getWidth(), getHeight());
        for (int i=0;i<elements.length;i++)
            elements[i].draw(g);
    }
}
```

## Lab Tasks

### Task 1: MSPaint!

In this task, you should create a simple painting app, to enable mouse events, you could call `enableEvents` method in your constructor:
```java=
enableEvents(java.awt.AWTEvent.MOUSE_EVENT_MASK);
```
then override `processMouseEvent` method, finally, you could store the graphics and draw over it, or store every mouse click position to draw it later!

Bouns: Make the right click change the color randomly!

**Note:** Please read the Java Docs!



###### tags: `Computer Programming II` `Lab` `IUG` `Computer Engineering`
<center>End Of Lab 4</center>