Lesson 4

First window

After introduction/strengthen lessons, now is the time to learn something related with a graphical interface. It is an interesting variety compared with what we had so far during studies.

I. JFrame class

import javax.swing.*;

public class Main {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame window = new JFrame();
            window.setSize(1024, 768);
            window.setTitle("Hello, world!");
Task 0

Move the code from the main method to a constructor of new class that extends JFrame.

Remember about creating an object of that class withing a lambda expression in main method.

Code is more origanized this way.

Task 1

Currently our window has a skype syndrome. If we will close it, it will not exit the program.

If you want to exit the program after closing a window, you need to add the following instruction to the view (window) class.

// If I close a window, I exit the program

II. Computer Graphics

Task 2

Write paint method in a class which extends JFrame.

Add a blue circle in a created window.

class A extends JFrame {
    A() {
    public void paint(Graphics g) {
        // We are setting RGB color for drawing
        g.setColor(new Color(255, 1, 100));
        // At the point (512, 512) we are drawing an ellipse with dimension 40x40
        // Notice: (0,0) point is located in top left corner of a window
        g.drawOval(512, 512, 40, 40);
Task 3

Methods getWidth(), getHeight() are used to get current dimension of a window.

Calculate (x,y) for the ellipse so it is always drawn in the center of a window.

Caution: consider, that you need (x,y) for top-left corner of a rectangle in which the ellipse is inscribed in.

Task 4

Run the program from the previous task and start resizing a window.

Task 5

Fix the bug seen in the previous task.

You can do this by calling paint method from the extended class before drawing an ellipse.

You can also use clearRect method on a Graphics object.

Task 6

Add new integer fields: x, y, radius to your window class.

Let paint method draw a circle in (x, y) with a radius radius.

Create an additional thread which will change values for those attributes.

Task 7

Make a circle bounce if on edge.