Sunday, March 8, 2015

Double Buffering with JFrames

Java games using the Swing library can oftentimes be tricky to render and implement, so here's an example of a very basic technique called double buffering that should simplify things.


import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;

public class DoubleBufferTest {


    public Canvas canvas;
    public boolean running = true;
    public BufferStrategy strategy;
    public int width = 600;
    public int height = 600;

    public DoubleBufferTest() {

        initAndRunUI();

    }

    public static void main(String[] args) {
        DoubleBufferTest test = new DoubleBufferTest();
    }

    public void initAndRunUI() {

        JFrame frame = new JFrame("Double Buffer Test");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        canvas = new Canvas();

        canvas.setPreferredSize(new Dimension(width, height));

        frame.add(canvas);

        frame.pack();

        frame.setVisible(true);

        run();

    }

    public void run() {

        canvas.createBufferStrategy(2);

        strategy = canvas.getBufferStrategy();

        while (running) {

            render();

            try {

                Thread.sleep(10);

            } catch (Exception e) {

                e.printStackTrace();

            }
        }

    }

    public void render() {

        Graphics g = strategy.getDrawGraphics();

        Graphics2D g2d = (Graphics2D) g;

        g2d.fillRect(0, 0, width, height);

        strategy.show();

        g2d.dispose();
        g.dispose();

    }

}

Okay! Our program will open a JFrame that renders a black screen, which is a great start
for any game. The code is a lot to take in, but here's the breakdown of what's happening:

The heart of our program is our run() method, which actually renders our screen. If you'll
notice, our screen is just a canvas we paint on. Some techniques involve having our
main class extend JPanel and add itself to the JFrame, but I find that using a Canvas is
generally more stable and easier to work with in the long run with larger projects.

The render() method is fairly simple, we just refresh our graphics every time by calling
strategy.getDrawGraphics(), which of course requires that at the start of our run() method
we actually create the strategy and store it in our variable. Other than that, using
Graphics2D draw methods is straightforward. Key note: don't forget strategy.show() and
g2d.dispose()!! These methods are key. Without show(), nothing is shown, and forgetting
dispose just means your program will gradually hog memory over time. This is called a
memory leak and should be avoided at all costs.

Also worth noting is that we aren't setting the size of our JFrame with the conventional frame.setSize()
method, but instead setting the preferred size of our canvas and adding it to the frame. This way,
when we call frame.pack(), we let Java handle arranging the frame's borders to best fit the canvas,
rather than fitting the canvas to the border.

Feel free to comment with questions or thoughts, I'd love to hear your feedback!


~N

The Variable

Phew, we've hit a lot of material lately, haven't we! However, the best is yet to come. We've learned about methods, classes, objects, etc...but all of that is pretty useless without today's concept, the variable.

Remember way back when in HelloWorld.java when we used System.out.println("Hello World!")? Wouldn't it be nice if we could have it print out something other than Hello World? We could edit the quotation marks and just change it manually, but what if we want to change it on the fly? What if we don't want to find that line of code and edit it manually every time? Turns out you can do it an easier way: using a variable.

Variables are objects that can store data and show data. I'm sure you know variables from math, where we can say "x=2", now plug X into the equation "4x-3" to get a result. The same holds true for code. We can say String statement = "Hello World!", and then use System.out.println(statement).

How do we create variables? We just say the "type" of the variable, (which we'll discuss in a minute), then whatever name you want to call it, and then what value it will hold. In Java, "=" is our assignment operator. Using = means you are setting the value of the object on the left to the value on the right. If we say "String aWord = 'hey'", that works. "hey" = String aWord does not work because "hey" isn't an object we can set a value to.

In essence, variables are just objects. When we create an object, we need to tell Java what kind of object we are creating. The most basic objects are called fundamental data types. Here are the most frequently used types:

  • int: An integer, with a value limit of around +- 32,000
  • long: An integer with a massive value limit of several million.s
  • double: A double-precision decimal number.
  • String: A phrase (or 'string') of text.
  • float: A more precise decimal with larger limits
  • char: A single charachter ($, %, a, .)
It's important to note that you can assign variable's values to other variables! If I have
int x = 10;
int y = 20;

I can then do:

int x = y;

And now x has a value of 20. However, you can only do this with objects of the same type! I can't assign a String to an int, or a char to a float.

Okay, let's put this good knowledge to use! Let's write a simple program to test our variables.

//I can use two slashes to make comments! You can type whatever you want
//And the compiler will completely ignore it. 
 
public class variableTester{

public static void main(String[] args){
System.out.println(statement);
System.out.println(number);
}

//Variables we use in our classes are called "instance fields"!
//Because we can make an object of our class and have more than one 'instance' of it.

String statement = "Low Key Coding is Bae";
int numberOfBlogViews = 67;
}

If we run this program, it will print out:

Low Key Coding is Bae
67

Perfect! That's the variable in a nutshell. Have fun!

~N

Thursday, March 5, 2015

Compilers, Errors, Classes, Objects, and Methods--Oh My!

Welcome back to basic programming in Java! Today we will be learning a TON of fundamental concepts vital to programming. If you don't want to read and learn...you might as well turn back now. That being said, let's hop in and get to it!

If you recall from the last post where we wrote HelloWorld, you might remember that all we had to do is click the "run" button in IDEA to run our code. However, there's a lot more going on behind the scenes that needs to be looked at to fully understand programming (I feel bad for neglecting this yesterday). When you click that run button, two things are happening: compiling and executing.

Compiling:
As you might have guessed, Java can't understand the lines of code you write. If you copied HelloWorld into the command prompt, nothing would happen. It doesn't 'mean' anything to the computer. So what does? In fact, there's some Java software called the Java Virtual Machine, JVM, that takes what you code and converts it into language the computer can understand. This important process is called compiling.

Code we write is stored in a file with the extension .java, which means we can edit it. However, as soon as you compile it, a new file is generated, a file ending in .class. If you try to read it, it looks like literal gibberish--but the computer understands it. So, why do we care?

Well, in fact, when you compile your program, it gets completely checked for any mistakes you made, these are called syntax errors. Think of them as spelling or grammatical mistakes in English writing. The Java compiler will make sure your program is 100% A-OK for running.

Once your program gets the thumbs up from the compiler, it gets turned into a .class file, which we'll just call a class file. It's important to note that since your .java file and your .class file are two separate files, you have to re-compile your code every time you want to run it. Lucky for you, though, IDEA compiles and executes in a single click. No worries!

Executing:

Once you have a class file, you can run it to your heart's content. Your class file won't change utnil you re-compile, which means your program will execute the exact same way every time until you change something. Moreover, since the compiler checked it, nothing *should* go wrong...however, things *do* go wrong, which brings us to:

Errors:

Oh no! Something has gone terribly awry! It sometimes happens that you, a fallible human, make a mistake. But fear not, the Java compiler is on your side! Any time an error happens, Java will (usually) tell you why, which means you know what to fix! Errors are easy to spot because they are big and annoying. Example:
Isn't the compiler nice? It tells us 1) that this is an error, 2) The line number and column number, and 3) what went wrong! In this case, I forgot to put a semicolon at the end of a statement:
So, easy fix, we just add our semicolon back, and we're good to go. The program compiles now. What we just did is called debugging or bugfixing, a vital step in software development. 

Tidbit: The phrase "debugging" comes from the era when computers were made using vacuum tubes. Occasionally a bug would fly into the tubes, and workers would literally have to de-bug the computer. 

It's worth noting that there are two main types of errors/bugs: compile-time errors, which happen during (you guessed it) compile time, and run-time errors, which happen when you execute the program. Doesn't make sense? Don't worry, we have a bit more to digest yet.

Classes:
When you compile a .java file, you get a class file, if you remember. Why is it called that? Well, and this is important, every file in Java is called a class. Every single line of code you write will be written in a class. Every single line, no exaggeration. Classes are important because, as we're about to discuss, you can make objects out of them!

Objects:
Look around your locale. What's the first thing you see? Ask yourself, "is that an object"? The answer is probably yes. Table = object. Floor = object. Air = object. It's the same way in Java. Every class you make has the capability to become an object, which means that you can have specific values that only that object has. Think about people. If Person was a Java class, that's great, but what if we have more than one person? We can't edit the code every time we have a new person. So we will make an object out of the person class. Now, we can have a Person object that refers to me, one that refers to you, and so on. Now each person can have their own describing values and traits. Don't worry if you can't wrap your head around this concept, it will make sense the more we discuss it. How exactly we make an object is for a post in the near future!

Methods (this is the last section, I promise):
So how exactly do we tell our program what to do? If you look back at our HelloWorld program, we basically have three lines of code that are interesting:
The first line is the start of our program. Every Java program starts with "public class AnyName", followed by curly braces to write your code in. So that leaves us with
So what are those? As it turns out, those are both what we call methods. Methods are how we tell Java what to do. Think of a method as an action that can be performed. You can turn on your computer repeatedly with a button--that's a method. You can eat food. That's a method. Any task you want to do in Java is a method. So how do we tell Java we have a method? Simple. You'll notice that the first line has four words in the first part: public, static, void, and main. Three out of these four are required in every method.

Public: This is the "scope" of the method. public methods can be 'used' (or in Javaspeak, called) from any other class, while private methods can only be called from within the class they're written in.

Static: The static keyword is optional at the start of a method. Static means that no matter how many objects we make out of this class, there will only be one instance of this method. For example, in our Person analogy, no matter how many People we have created, there will only be one main method. No more. Uno. No mas. Don't worry about static though, it's a bit more of an advanced topic.

Void: This is the return type of a method. This will make more sense when we learn about fundamental data types, but this basically tells the Java compiler what kind of output or return we can expect from this method. Is it going to give me a number? A word? That's what the return type tells you. In this case, void means that the method won't give the JVM anything in return.

main: This is just the name of your method. It can literally be anything, with a few exceptions. You can't use special characters like % or @, and you can't use certain reserved words like main, public, void, etc. Don't try to be a smartalec about it, and you'll be fine.

Finally, what's in those parentheses? In fact, those parentheses come after the name of your method, and they are vital--they tell Java what kind of information your method needs to run. If my method is "computeAverageGrade", I'll need what? I'll need several scores to average, right? Or, maybe if my method is called "watchPaintDry", I don't need any information--I just do it. Those parentheses contain what we call the parameters of the method. 

So let's put it all together! If you want to name a method, you write the scope, followed by static or not, (if not, just skip it), then the return type, (void for now), and then the name and parameters (nothing, for now). Let's make a sample method called eatPizza!


See how simple it is? We chose public by default, we skipped static because that's the default choice we should pick, we chose void again because it's default, and then we chose the name eatPizza, followed by empty parentheses because we don't want any information. 

That method at the start of HelloWorld is your main method, which needs to be in every program you write. It tells the compiler where your program starts. The main method is where your program begins, every time. 

Phew that was a lot! Sorry it took so long, but you've gotta understand these concepts before we can program. Hope you enjoyed even a little bit! Please feel free to comment or email me with any inaccuracies or questions. Thanks for reading!

~Nathan

Advanced, Completely Unnecessary Tidbit: You might have noticed that in our discussion of public static void main(String[] args), we left out the topic of String[] args. Those are actually just a parameter, like we discussed. Since the main method is the start of our program, there's no way for us to "call"  it within our program. Actually, the main method is called by the Java Virtual Machine, and that parameter means that the main method needs "an array of arguments" to run. Just like how eatFood would need a parameter of what food we're eating, the main method requires a list of "arguments" which are specific ways to execute our program. We can't control them, but it's interesting to know what that means.




Wednesday, March 4, 2015

Your First Java Program

Java is used on over 6 billion devices worldwide. It has been in development since the 1990s by Sun Microsystems; and slowly became one of the top languages for software and applet development. Hopefully this post will teach you the basic knowledge necessary to run your first program in Java!

I: Setting Up Your Machine
There are two main types of Java: 'vanilla' java for the everyday user, or the Java Development Kit for users who want to compile their own Java code (that's us!).  If you've had your machine (a fancy word for computer) for more than a few days, chances are you've installed vanilla Java--it's used for just about everything. However, you'll need the JDK, so let's head over to the Java website to download it. Here's the link to the Java 7 SDK downloads, or, alternatively, Java 8 SDK downloads. Simply look in the first chart for your system, and download it. It should install itself.

Tidbit: Wondering which version of Java your machine is running? Open up the console and type "java -version". 

Mini-tidbit: Unsure where your console is? On windows, use Windows Button + R to open the Run prompt, then type "cmd" and hit enter. On OS X, simply open Finder and type in "console". 

Once you've completed the download and installation of the JDK, you're ready to code! There are two routes you can take from here:
  1. Use a simple text editor such as Notepad or Notepad++ to write your Java. (this requires a bit more gritty work to 'compile' your code, more on this later)
  2. Use an 'Integrated Development Environment' or IDE. IDEs provide a streamlined and easy way to edit, compile, and run code with a single click. This is what I recommend you do!
We're going to assume you want to take the easier route, you lazy person, and use an IDE. I highly recommend using IntelliJ's IDEA, which can be found here! Simply download the community version and run the installer. Now we're finally ready to get going!

II: Our First Program
Alright, we're all set up and ready to go! The first thing you should do is open up IDEA and create a new project. Call it "HelloWorld". In Java, it's customary to always use what we call 'camel case', which means that every new word is capitalized. So, "anewprogram" would become "ANewProgram". 

Tidbit: It's worth noting that the first letter is always lowercase, unless we're naming our program. 

At this point, you should have something like this:



Now let's make our first program! Simply right click the blue folder labeled "src", and click New > Java Class. We'll name it HelloWorld as well.

And now we have a beautiful blank file to code!
For your first program, make a new line between the two curly braces and type the following:
Your whole program should now look something like this:

Now the moment of truth! Go to the Run tab and click Run, then hit Enter if prompted! Cross your fingers.
If your box looks like my box, PERFECT! Well done! You've just written your first program! Does it feel amazing? Can you sense the raw power flowing through your fingertips? Good. You should. Tune in next time for an analysis of what in the world we actually typed in that program, and what it means! Until then, try inserting different phrases in those quotation marks, and see what you can get your computer to say!

Until next time,

Nathan