Alan Abraham
Alan Abraham

Reputation: 103

Trying to understand Java game design code

I am trying to learn game design in Java and I am following a tutorial. The tutorial gives this code, but not a lot of elaboration. I had some questions regarding Java and graphics.

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Game2 extends JPanel {

    @Override
    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.RED);
        g2d.fillOval(0, 0, 30, 30);
        g2d.drawOval(0, 50, 30, 30);        
        g2d.fillRect(50, 0, 30, 30);
        g2d.drawRect(50, 50, 30, 30);
    }
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("Mini Tennis");
        frame.add(new Game2());
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Why do we need to extend JPanel into the class Game2? I have never used extends on my main class, so I'm not sure what it means in this case and why it is necessary.

What does frame.add(new Game2()); mean? Why are we allowed to make a new Game2() within the Game2() class?

What are the Graphics and Graphics2D objects? Also couldn't we just use a Graphics2D object as the parameter of paint() since we never use g outside of typecasting it to a Graphics2D object.

Lastly, why don't we need to call paint()?

Upvotes: 0

Views: 76

Answers (1)

Newerth
Newerth

Reputation: 574

You can extend (almost) whatever component you like. The crucial thing here is that you put the component onto a JFrame which makes it a base for the new window. Using JPanel is good because it contains no graphics and therefore can serve as plain canvas.

frame.add(new Game2()) puts the JPanel you're extending into a JFrame.

You can create class instances freely wherever you want as long as they're visible to you in the given scope.

An instance of the Graphics2D class is passed to the paint() method automatically whenever the underlying operating system decides it's time to redraw the component (for example upon showing the window or dragging another window over the component).

The parameter is always of type Graphics (meaning that the value can be of the same type or any class that extends it). This is given by the definition of the method (meaning that some of the parent classes or interfaces declares it like this) and you cannot change it.

Please take some time to get acquainted with the basics of object oriented programming before you start with anything more complicated:

https://www.w3schools.com/java/java_oop.asp

Upvotes: 1

Related Questions