Try โ€‚โ€‰HackMD

Programming II Lab 4

More about Inheritance

The Islamic University of Gaza
Engineering Faculty
Department of Computer Engineering
Author: Mohammed Nafiz ALMadhoun2021/03/05

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.

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.

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.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More โ†’

Figure 1: JFrame

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.

... 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.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More โ†’

Figure 2: JTextField

There is a lot of components that you could use, take a look at this docs.

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:

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, 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.

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!

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); } }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More โ†’

Figure 3: Extending JPanel

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!

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.

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!

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:

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: Programming Java IUG
End Of Lab 4