Notes by
Ben Borgers
F’22
super(x, y)
to run a constructor from the parent class.
x, y
you choose determines which constructor is called.super.methodName()
to call a method in the super class.// 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);
}
}
g.setColor
g.fillRect(0, 0, 10000, 10000)
(just making a huge rectangel that’s bigger than the screen).
getSize()
to be more precise.Graphics2D
is a more modern and more powerful version of Graphics
.