September 28th, 2022

OOP for GUI

  • In a subclass’ constructor, you can use super(x, y) to run a constructor from the parent class.
    • The x, y you choose determines which constructor is called.
    • There’s also super.methodName() to call a method in the super class.

Drawing

// Main.java
import java.awt.*;
import javax.swing.*;

public class Main extends JFrame {
    public static void main (String [] args) {
	java.awt.EventQueue.invokeLater (new Runnable() {
            public void run() {
		new Main ();
            }
        });
    }

    public Main () {
	// Window setup
	setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
	setSize (300, 300);

	// Put a Canvas in
	Canvas canvas = new Canvas ();
	add (canvas);

	// Show the window
	setVisible (true);

	// No drawing here, do it in Canvas callback

    }
}
// Canvas.java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class Canvas extends JPanel {
    // This is the draw callback
    public void paintComponent (Graphics g) {
			super.paintComponent(g);
			g.drawLine (50, 50, 100, 50);
    }
}

Commands for drawing.

  • g.setColor
  • Change background color by doing g.fillRect(0, 0, 10000, 10000) (just making a huge rectangel that’s bigger than the screen).
    • Later we’ll do getSize() to be more precise.

Graphics2D is a more modern and more powerful version of Graphics.