We've already learned the following drawing commands: |
There are also the following Swing commands that have been simplified for HSA2: |
|
|
Making a colour
Color c = new Color(r,g,b);
//where r,g,b are numbers representing red, green, blue values
and which range from 0 to 255.
Making a new Font:
Font f = new Font("Arial", Font.PLAIN, 24);
//the second parameter can be PLAIN, BOLD, or ITALIC
IMPORTANT: Don’t create fonts inside a loop. They take up a lot of CPU time.
Comparison
Typical Graphics program |
Typical Text-based program |
public class BestGraphics { public static void main (String[] args) { new BestGraphics(); } //global variables GraphicsConsole gc = new GraphicsConsole(); int health = 50; BestGraphics() { //do stuff ... most of the program goes here drawGraphics(); } //other methods go here, most will be void void drawGraphics(){ //draw healthbar gc.drawRect(10,10, 100, 20); gc.fillRect(10,10, health, 20); } } |
public class BestProgram { //global variables: all must be static static int secretNum = 78; public static void main(String[] args) { //do stuff ... int x = calculateSomething(56); } //other methods can go here, but they must all be static static int printAnswer(int num) { int result = secretNum * num; return result; } } |
Nothing needs to be static.
Constructors
|
Everything needs to be static. We'll learn about static in Grade 12 when we learn about objects. |
public class ProgramName { public static void main(String[] args){ new ProgramName(); } //global variables GraphicsConsole gc = new GraphicsConsole(); Ball b; Enemy e; //***** constructor ****** ProgramName(){ setup(); while(true) { --> start loop //move whatever needs moving moveBall(); moveEnemies(); movePlayer(); moveSolarSystem(); //check for whatever collisions might occur hitWall(); //player hits wall shootEnemy(); //bullet hits enemy deathByBlackHole(); //solar system hits black hole drawGraphics(); // ALL graphic drawing goes here and is put inside a "synchronized(gc){ }" code block. gc.sleep(n); //sleep for some number of milliseconds to let the graphics get drawn properly } <--- end loop (go back to start) //any program cleanup goes here, which is AFTER the loop exits //write out high score to a file ... gc.showDialog("Thanks for playing","Game Over"); gc.close(); } //all other methods go here: void setup() { ... } void moveBall() { ... } void shootEnemy() { ... }
First understand that the while() will keep looping. Everything inside the purple lines will happen over and over again.
Pressing 'Q' or 'q' will quit the loop.
The program will then proceed to the lines after the loop:
gc.showDialog("Thanks for playing","Game Over");
gc.close();
Before we run the loop, we need to set up the screen. I’ve made a subprogram called setup() to do this.
Subprograms are called methods (functions or subroutines). For simple graphics, they normally have void in front of them.
Other methods each do one specific task: moveBall, checkCollisions, drawGraphics.