Chapter 1. Getting Started with Java

Java can be a complex programming language and a challenge to learn in its entirety, but it is easy to get up and running very quickly using freely available development tools and basic code. Java is one of the most rewarding programming languages I have used, and I’m sure you will agree as you gain experience with the language that it’s worth your investment of time. This chapter will help you get started with Java and will be especially helpful if you have had no prior experience with this language. This chapter explains what you need, where to get it, and how to configure your system to prepare it for building Java-based games. Several Java-enabled development tools will be presented so you can choose the one that will best meet your needs, including TextPad, NetBeans, Eclipse, and command line.

Here are some of the topics that will be addressed in this chapter:

  • Java and the web

  • The casual games market

  • Installing and configuring Java

  • Your first Java program

Java and the Web

Let’s take a look at game design for a moment and see how Java fits in, because this is the core subject of the book. What truly has changed in the world of gaming since the “good old days”? By that term, I am referring to the infancy of the game industry that entertains the world today, back in the 1980s when arcade game machines were at the top of their game. Many readers were probably born in the 1980s and have no recollection of the games of that era, except perhaps those that were ported to the second-generation consoles of the early 1990s (Nintendo SNES, Sega Genesis, Atari Jaguar). You have seen the various anthology collections from Namco, Atari, Midway, and Taito, featuring classics such as Joust, Dig Dug, Pac-Man, Space Invaders, Defender, and others (some of which date back to even the 1970s).

Note

Nintendo has given some of its classic games an overhaul and released them on the extraordinary Nintendo DS handheld system. Good move! Not only are some classics, such as the original Super Mario Bros., outselling most other handheld games, but re-releases, such as The Legend of Zelda: A Link to the Past (for the Game Boy Advance), have outsold most console and PC games.

Studying the Market

The game industry is pushed forward by gamers, not by marketing and business executives, which makes this industry somewhat unique in the world of entertainment. Isn’t it obvious that professional sports (NFL, NBA, NHL, and MLB here in the States) are not advanced or directed by the fans? On the contrary, the fans are often derided and ignored by not only the team franchises, but by the organizations themselves. This is an example of how centralized management can lead to problems. Unfortunately for sports fans, they are more than willing to put up with the derision given to them because they love the sport. This is a level of loyalty that simply doesn’t exist in any other industry. If you love sports, you ignore all the problems and just enjoy the game, but that doesn’t change the fact that it’s a seller’s market (although digital entertainment is drawing fans away from professional sports in droves).

How is the game industry a buyer’s market (meaning, gamers have a lot of influence over the types of games that are created)? Most games are created specifically for a consumer segment, not for the general public. The decision makers at game publishing companies choose projects that will reach as many core constituents as possible, while also trying to reach casual gamers and hardcore fans of other game genres. For instance, Blizzard Entertainment (a subsidiary of Vivendi Universal Games, which also owns Sierra Entertainment) targets mainly two genres: real-time strategy games (WarCraft series, StarCraft), and role-playing games (Diablo series, World of WarCraft).

Can you think of a game that Blizzard has published that does not fit into these two genres? Blizzard has consistently hit the mark dead on with their games in terms of target audience, quality, polish, and subsequent mass appeal. World of WarCraft has sold millions of copies with millions of simultaneous players supported on its multitude of servers. WarCraft III has sold more than five million units (including the add-ons), while the entire WarCraft series has sold twelve million units since its debut in 1994. StarCraft has sold nine million copies since 1998 (including add-ons), while StarCraft II, released this year, increases the series total.

Why do you suppose Blizzard has been so successful? Certainly not through aggressive advertising campaigns! Gamers have traditionally been immune to marketing, relying primarily on word-of-mouth recommendations from friends, online review sites, and bloggers for their game purchase decisions. If any of Blizzard’s games had not been up to par with the gamers, they would not have continued to play the game. But the sales figures shown here reveal products that have had a very long shelf life due to continued sales.

Design Rules

I could go into other companies with equally impressive success stories, as well as those that have been dismal failures. But my goal is to demonstrate to you that the game industry is indeed a buyer’s (gamer’s) market. It’s not dictated and ruled by the board of directors of one company or another or by marketing people, who have been stymied by the reluctance of gamers to go along with traditional promotional theories. In other words, gamers are a tough audience! It’s an empowering position to be in, knowing that your personal preferences and tastes are shared by millions of others who demand excellence and innovative gameplay, and that these demands are met, more or less. Companies that produce excellent games are rewarded by gamers, while those that fall short quickly close up shop and move on.

Would you like another real-world example? A few years ago, a new publisher emerged in the game industry by the name of Eidos. This company’s bank account was padded by millions of PlayStation owners who had all fallen in love with Lara Croft. Eidos seems to have misinterpreted the market, believing that gamers loved the image and motif of this Bond-esque heroine. Eidos created a new hotshot team in Texas made up of some industry veterans in an endeavor called Ion Storm. The belief was that marketing the “rock-n-roll” hype of these developers would lead to millions of preorder sales for their games (coming from the successes of the two Tomb Raider sequels).

Eidos failed to recognize that gamers bought into Lara Croft because the games were fun, not because of the image. When Ion Storm was launched, Eidos printed two-page spreads in major game magazines showing the team rather than the upcoming games in development. The developers of Daikatana were not able to keep up with the marketing explosion and were derided for producing an average game that would have been well received were it not blacklisted by gamers after years of hype. The impression was very strong that it was all about sales, not a gaming experience, and gamers rejected that notion. Eidos has moved on from the experience too, having published some fantastic games such as LEGO: Star Wars, Deus Ex, and Anachronox.

In my experience, the fun factor of video games has risen exponentially in the last two decades, along with the complexity of modern games. Let’s face it; you can only play Pac-Man for an hour or so until it becomes tedious. The same applies to most of the classic arcade games. At one time, you could fit every video game in existence in a single room, and those quarter-fueled machines were housed in stand-up cabinets. Since that time, there have been about a half million games created, though we might narrow down that figure to a few thousand good games, out of which we find a few hundred “Hall of Fame” greats.

The Casual Games Market

In recent years a new game genre called casual games arose in the game industry. This genre has been relegated to secondhand status for many years, while the numbers of gamers has risen from the hardcore “geek” fans to include more and more people. The average gamer plays games for a few hours a week, whereas the hardcore gamer spends 20 or more hours playing games every week (like a part-time job). Casual gamers, on the other hand, will only spend a few minutes playing a game now and then—perhaps every day, but not always. The casual gamer does not become addicted to any game the way a hardcore gamer does, with games such as World of WarCraft, Star Wars: The Old Republic, Lord of the Rings Online, and so on.

So, what is a casual game anyway? A casual game is any game that can be played in a short timeframe and requires no instructions on how to play. In this context, almost every classic arcade game ever made falls into this category. It is only recently that publisher and game industry pundits have begun to realize that gamers really don’t want the long, drawn-out experience of installing a game, downloading a patch, and spending eight hours learning how to play it. Sometimes it is refreshing to just fire up a game and play for 10 or 20 minutes without having to screw with it all evening! This was a gripe of mine for a long time. It is why I spend far more time playing console games than PC games, and I’m sure many readers share that sentiment.

No Manual Required

Yes, there are some PC games that are so compelling or innovative that they are worth the effort to get them installed and running. The best example of late is World of WarCraft. I have spoken to many gamers who claim that if Blizzard’s games were not so darned much fun, they would boycott Blizzard altogether! (How’s that for a contradiction?) The impression I get is that these gamers have a love/hate relationship with Blizzard and many other game publishers as well. (Lest you suspect that I suffer from memory lapse over Blizzard, let me clear up one important point—I love their games, but dislike their terrible installers!)

Case in point, I could not install World of WarCraft on my decently equipped laptop. First, the installer locked up and a subsequent install attempt reported an error on disc two. I got around these issues by copying all four discs to the hard drive and installed it from there with no more problems. However, as soon as I fired up the game and logged in to my account, it dropped out to download a 260MB update to the game. When that was done, three more small updates were installed just to bring the game up to the latest version. Are these problems tolerable? Yes and no. On the one hand, this is the most advanced and complex MMORPG (massively multiplayer online role-playing game) ever created, and Blizzard has a full-time team continually creating new content and improving the game, which I applaud. But on the other hand, that sure was a lot of work just to get the game installed, and it took three hours of my time (which is why hardcore gamers tend to have more than one PC).

Would a casual gamer be willing to devote that much time just to install a game that will end up requiring hundreds of hours of gameplay in order to rise through the ranks within the game world? Most casual gamers do not have the time or patience to jump through so many hoops for Blizzard, unless a friend helps them get started. Such is the target audience for casual games! Have you ever given serious thought to this issue? If you are an IT (information technology) professional or a hardcore gamer, you are used to dealing with computer problems and coping with them without incident. But do you ever wonder, if you—a smart, experienced, knowledgeable computer expert—are having problems with a game, how on earth will an average user figure out these problems? Well, the short answer is, they don’t, which accounts for most game returns.

Casual Games

Casual gamers include professionals such as doctors and lawyers, business executives, software developers, and, well, everyone else. Casual games attract people from all cultures, classes, genders, religions, ethnicities, and political orientations. Given that most potential game players are not willing or able to cope with the issues involved in PC games, is it any wonder that this burgeoning market has been inevitable for several years now? While casual games are currently played mainly in a web browser using technology such as Java and Flash, the console systems are featuring online gameplay as well, and this trend will continue to gain popularity.

The casual game market was limited a few years ago. Only recently has this subject started to show up on the radar of publishers, schools, and retail stores, even though gamers have been playing casual games for two decades. (I predicted casual games would take off a few years ago, but my dog ate that article.) Casual games are a win-win situation because they are just as easy to create as they are to play, so the developer is able to create a casual game in a short timeframe, and the gamer has an enjoyable experience with a lot of choices. Casual games have a very simple distribution model (most are put up on a website for online play), a respectable compensation model (developers receive a percentage of net sales or a single lump sum), an often meager development cycle measured in weeks or a few months, and almost no testing required. As a casual game developer, you can come up with an innovative game idea, develop the game, and get it onto store shelves (that is, a website) all within the timeframe of just the concept-art stage of a full-blown retail game.

Jay Moore was an evangelist for Garage Games who promoted the Torque game engine around the country at conferences and trade shows. He spoke at the 2005 Technology Forum at the University of Advancing Technology, where he addressed the possibility of earning a living as a casual game developer. Garage Games’ Torque engine has been ported to Xbox 360, and they have published two games on Xbox Live Arcade that you can download and play if you are a Live user. Marble Blast is one such game, and Garage has many more games planned for release on Live and through retail channels. In fact, when you purchase the entire Torque game engine for $100, you have the option of publishing through Garage Games, which does the contractual work and provides you with a contract (subject to quality considerations, of course).

Microsoft has really embraced casual games by making it possible for independent developers to publish games directly on Xbox Live Arcade without going through retail channels. Xbox 360 is the first console video game system in history to provide downloadable games right out of the box without first purchasing retail software. If you are interested in casual games, you can enjoy playing on Xbox Live Arcade without buying a retail game at all, because many games are available for free trial and purchase on Xbox Live Arcade (with a membership account, that is). Indie developers can use XNA Game Studio to develop games for Windows, Xbox 360, Zune, and Windows Phone 7 for a small annual membership fee.

I attended the Austin Game Conference in 2005, and the focus of the show was about casual games. Microsoft’s booth was titled “Microsoft Casual Games,” and they were giving away USB flash drives with the MSN Messenger SDK and showcasing some of their Xbox Live Arcade games, as just one example. These early efforts to promote casual game development on Microsoft’s platforms has paid off in a huge way today with Xbox Live seeing huge earnings for both Microsoft and all of their publishers and indie developers alike, thanks to a very reasonable 70/30 royalty rate.

One of the earliest downloadable games on Xbox Live Arcade was RoboBlitz. This game was built using the Unreal Engine 3 (which Epic Games developed for Unreal Tournament III). RoboBlitz also makes use of the impressive Ageia PhysX physics engine to produce realistic gameplay. Another innovative game on Xbox Live Arcade from the creators of Project Gotham Racing is Geometry Wars. This game is unique and compelling, with gameplay that involves gravity and weapons that resemble geometric shapes.

If you feel as if I’ve been leading you along a train of thought, you would be right to trust your feelings. The focus of this book is about programming games using Java with a strong emphasis on casual games, and we will learn to do just that shortly. Since Java is the pioneer language of casual game development, I will be emphasizing this aspect of gaming while creating web-based projects in the chapters to come. But for those interested in just Java game programming without concern for the web or the casual market, most of the projects will be presented as standalone applications that do not need AppletViewer or a web browser.

Installing and Configuring Java

As you might have guessed, Java applet games run in a web browser—Internet Explorer and Mozilla Firefox work equally well for running Java games. Java programs can also run on a desktop system locally without going to a website. These types of programs are called Java applications and require the Java Runtime Environment (JRE) to be installed. The web browser runtime is the same as the desktop application runtime, which is installed with the JDK. Users who do not need the Java development tools will just install the JRE, which is what happens when a user installs “Java”—a reference to the JRE.

When you install Java Standard Edition 6 (Java SE 6), the runtime includes an update for web browsers automatically. So if you write a Java game using features from Java SE 6, the runtime might need to be updated on an end user’s PC before it will run the game properly. In some cases, the compiled Java program (which ends up being a file with an extension of .class or .jar) will run on older versions of Java, because some updates to the Java language have no impact on the resulting compiled files. The games we write will run as an applet or as an application with a little bit of tweaking. In the interest of simplifying the code as much as possible, we will create an application in most cases using a JFrame. Why?

A JFrame gives us the Graphics context we need to draw with Java 2D. An Applet project has a Graphics context, but a standard console-style application does not, unless a JFrame is used. What this does is give us a window for drawing. By default, an application will just work with the console for text input and output, but we need a graphical window on which to render, and that is what a JFrame provides. It’s actually very easy to use, and we’ll begin working with it soon.

Installing Java

The Java SE 6 development kit is available for download from http://www.oracle.com/technetwork/java/javase/downloads. You will want to get the latest version of the JDK, which is “Update 22” at the time of this writing (see Figure 1.1). When you install the JDK, the installer will not automatically modify your system’s environment variables, which is something we will need to do so that you can run the Java compiler (javac.exe) using a command prompt or shell window. The current version at the time of this writing is Java SE 6 Update 22, and the install file is calledjdk-6u22-windows-i586.exe. If you are using a system other than Windows you will need to visit the Java website to download the appropriate version for your system.

Installing Java SE 6.

Figure 1.1. Installing Java SE 6.

Tip

Since the second edition of this book was published, Sun Microsystems (the developer of Java) was acquired by Oracle. So, Java is now an Oracle product.

Configuring the Java Command-Line Compiler

Java will be installed by default in the folder C:Program FilesJava (on the Windows platform; obviously, this will be different depending on your system). In this folder are two folders called jdk1.6.0_22 and jre6, containing the development kit and runtime environment, respectively. We need to focus our attention on the first folder containing the JDK, in particular. This folder contains a folder called bin, in which you will find all of the Java programs needed to compile and run Java code. The most important programs in this folder are javac.exe (the Java compiler) and appletviewer.exe (the applet viewer utility). We need to add this folder to the system’s environment variables so that we can invoke the Java compiler from any location on the hard drive.

I’m going to focus my attention on Windows since it is the most widely used operating system. Depending on the system you’re using, the steps will be different but the concept will be similar. You need to add the jdk1.6.0_22/bin folder to your system path—the list of folders searched when you invoke a program at the command line. In Windows, open the Control Panel and run the System utility. Select the Advanced tab, as shown in Figure 1.2. Here you will find a button labeled Environment Variables. Click on it.

The System utility in Windows Control Panel.

Figure 1.2. The System utility in Windows Control Panel.

Tip

The System Properties dialog in Windows 7 can be found in Control Panel, System, Advanced system settings.

Scroll down the list of system variables until you find the Path variable. Select it, then click the Edit button. Add the following to the end of the path variable (including the semicolon):

;C:Program FilesJavajdk1.6.0_22in

If you have installed a different version, you will need to substitute the version shown here with the actual folder name representing the version you installed on your system. Click the OK button three times to back out of the dialogs and save your settings. Now let’s verify that the path has been configured properly by testing the Java installation.

To open a command prompt in Windows, open the Start menu, Program Files (or All Programs), and you will find it in Accessories. The command prompt should appear as shown in Figure 1.3.

Adding the JDK folder to the system path.

Figure 1.3. Adding the JDK folder to the system path.

If you are using a system like Linux, just open a shell if you don’t have one open already, and the commands and parameters should be the same. Now that you have a command prompt, type the following command and press Enter:

javac -version

This will invoke the Java compiler and instruct it to merely print out its version number, as shown in Figure 1.4. The version reported here is just what you would expect: 1.6.0_22 represents Java SE 1.6 Update 22.

The Java compiler reports its version number.

Figure 1.4. The Java compiler reports its version number.

If you were able to see the version number show up on your system, then you will know that Java has been installed correctly, and you’re ready to start writing and compiling code! On the other hand, if you received an error such as “Bad command or file name,” then your environment variable has not been set correctly, as explained previously. There is an alternative to editing the system’s environment variable—you can just modify the path from the command prompt. However, when you do this, the change is not permanent, and you will have to set the path every time you open a command prompt. But just for reference, here is how you would do it:

set path=%path%;C:Program FilesJavajdk1.6.0_22

At this point, you are ready to start writing and compiling Java code. So let’s do just that, to further test your Java installation. In a moment, we’ll write a Java application that prints something out to the console (or shell). See the section below titled “Your First Java Program.”

Java Version Numbers

Java’s versioning can be confusing, but it’s something you might want to understand. The official latest version of Java at the time of this writing is Java Standard Edition 6 Update 22, or Java SE 6u22. However, the actual version number is 1.6.0. The computer industry is anything but consistent, given the extraordinary changes that have taken place on the Internet and in software development in general. But one thing has been agreed upon in the computer industry regarding versioning. The first release of a software product is version 1.0. Often a revision or build number will be appended, such as 1.0.8392, which helps technical support or call center personnel identify the version or sub-revision of software that a customer is using when a problem arises. The revision number is, in every case, not part of the retail packaging and product name, but rather a tracking tool. Table 1.1 lists the Java version history.

Table 1.1. Java Version History

Year

Version

Marketed Name

Code Name

1996

1.0

Java 1.0

 

1997

1.1

Java 1.1

 

1998

1.2

Java 2

Playground

2000

1.3

J2SE 1.3

Kestrel

2002

1.4

J2SE 1.4

Merlin

2004

1.5

J2SE 5.0

Tiger

2006

1.6

Java SE 6

Mustang

2010

1.7[*]

Java SE 7

Dolphin

[*] 1.7 is still in a pre-release state at the time of this writing, as it has been for two years.

The interesting thing about this table is that it is very consistent in the second column (Version), but there are a lot of inconsistencies in the third column (Marketed Name), which is not a great surprise since marketing campaigns seldom makes sense. If you were to follow the progression from one version to the next and tally them, you might note that there have been seven major versions of Java (while the eighth version is 1.7, and not yet released). Product branding is a very expensive and time-consuming process, which is why businesses defend their brand names carefully.

When Sun released Java 2 as a trademarked name, the name caught on, and the version we are using now, Java SE 6, is still known internally as version 1.6.0. Java fans love these quirks, which are not flaws but endearing traits, and it’s not a problem once you understand how it has evolved over the past decade.

Java SE 6 Development Kit

The Java SE 6 Development Kit (the “JDK”) is available for these platforms:

  • Linux

  • Linux Intel Itanium

  • Linux x64

  • Solaris SPARC

  • Solaris x64

  • Solaris x86

  • Windows

  • Windows Intel Itanium

  • Windows x64

We are focusing primarily on the Windows platform because that is the most popular platform, but the code and examples will absolutely build and run on all of the supported platforms without any modifications.

There are several components that extend the basic functionality of Java that are of interest to us with regard to game programming.

Java 2D is an API containing classes for advanced 2D graphics rendering and image manipulation, with support for vector (line-based) shapes, font-based text, image formats, and advanced RGBA color manipulation. This API works great for building 2D games with Java, and is what we will be using in this book. Among other things, we can perform transforms (rotation, translation, and scaling) on 2D images.

Java 3D is an API that allows rendering of 3D graphics in a Java application or web-based applet with high-level constructs for building 3D scenes. The websites are java3d.dev.java.net and www.java3d.org. This API works very well for building 3D games with Java.

Java Development Environments

There are a variety of Java development environments we can use for our Java game projects, from the fairly large and complex Eclipse to a text editor with command-line compiler. In most cases, you will want to install the Java Development Kit (JDK) first, because all of the integrated development environments (IDEs) require the JDK.

Caution

The JDK must be installed first if you choose to install and use an IDE such as Eclipse or NetBeans. These IDEs support Java, but do not include the JDK, and the JDK is a prerequisite in order for the IDEs to automatically locate and plug in links to the JDK if it’s installed. If you install an IDE first, then it won’t be automatically set up and you will have to manually link it to the JDK. Optionally, you may install a special version of NetBeans with the JDK.

Command Prompt/Shell

The simplest way to create and run a Java program is with a text editor and the Java command-line tools javac.exe, java.exe, and appletviewer.exe. Any text editor will work, including Notepad, although there are better choices out there, some of which offer Java source code syntax highlighting to improve your productivity. The point is, once you have installed the JDK, you can technically get by with nothing more than this. In many ways, just using the simple command-line tools is preferable to the large and complex projects created by the professional IDEs, which is why I often take this route when I just want to write a small program in Java. If you are using Linux or Mac OS, then the shell is likely your preferred choice.

TextPad

One such editor with Java source code highlighting is TextPad, available for download from www.textpad.com. We’ll be using TextPad quite a bit in the next section of this chapter so I’ll refer you there for screenshots showing what TextPad looks like. There are many other editors like TextPad, but TextPad is unique (and helpful!) with its built-in support for the JDK tools that makes it possible to compile and run Java code right from inside the text editor. The latest version of TextPad (5.4 at the time of this writing) now supports a Workspace feature, which puts TextPad into the realm of a “mini IDE.” A project workspace in TextPad can now be saved so that all of the configured tools and source files are retained in the project, saved to a workspace file with an extension of .tws. Since TextPad is so incredibly easy to use, this will be our tool of choice, with NetBeans a close second.

NetBeans

NetBeans IDE (currently at version 6.9.1) is a free development environment with support for Java, C++, PHP, and Ruby projects, and is available for Windows, Mac OS, and Linux. This is the official development environment for Java. The complete NetBeans distribution requires a separate installer for the Java Development Kit (JDK), and it can be downloaded from http://netbeans.org. Another distribution of the JDK is available with NetBeans 6.9.1 already included! If you are new to Java development, then this is the version I recommend using because it only requires one install to get both the JDK and IDE up and running. If you have already installed the latest JDK, then just use the independent NetBeans installer.

Eclipse

Eclipse is another community-supported development environment with support for multiple languages, including Java. The home page for Eclipse is at www.eclipse.org. There is a package for Java development ready to be downloaded and installed called “Eclipse IDE for Java Developers” at http://www.eclipse.org/downloads. Eclipse can be rather difficult to use, especially if you’re really new to programming, but it is jam packed with incredible features right out of the box, so to speak, and is a quite mature development environment. But, with complexity comes difficulty of use. In fairness to the developers and fans of Eclipse, we will at least see a simple example of an Eclipse project later in the chapter but it will not be our tool of choice.

Your First Java Program

I want to take you through the steps of creating a new Java program to test the JDK and a Java applet project to test web-browser integration right away so we can begin programming. Let’s start at the very beginning so that when you have written a full-featured game down the road, you’ll be able to look back and see where you started.

Java Application

The following program, shown in Figure 1.5, is called DrinkJava. Type it into a text file and save the file as DrinkJava.java.

The DrinkJava program can be edited using any text editor.

Figure 1.5. The DrinkJava program can be edited using any text editor.

import java.io.*;
public class DrinkJava {
    public static void main(String args[]) {
        System.out.println("Do you like to drink Java?");
    }
}

Tip

The perhaps undocumented but assumed coding standard for Java has always placed opening brackets for a small block of code at the end of a statement. Large blocks of code typically have the bracket on the next line to improve readability and reduce potential bugs. You may feel free to put opening brackets on the next line if you prefer. I am doing it this way to stay in line with the JDK examples.

Now let’s compile the program. You’ll need to open a command prompt window again, or you can continue using the one discussed earlier if you still have it open. Use the cd command to change the directory to the where you saved the .java file—for instance, cd chapter01DrinkJava. Once in the correct folder, you can then use the javac.exe program to compile your program, assuming you have added the JDK to the system path as described earlier:

javac DrinkJava.java

The Java compiler (javac.exe) should spend a few moments compiling your program, and then return the command prompt cursor to you. If no message is displayed, that means everything went okay. You should then find a new file in the folder called DrinkJava.class. You can see the list of files by typing dir at the command prompt, or just open Windows Explorer to browse the folder graphically.

To run the newly compiled DrinkJava.class file, you use the java.exe program:

java DrinkJava

Note that I did not include the .class extension, which would have generated an error. Let Java worry about the extension on its own. By running this program, you should see a line output onto the command prompt like this:

Do you like to drink Java?

Perhaps without realizing it, what you have done here is created a Java application. This is one of the two types of Java programs you can create. The other type is called an applet, which describes a program that runs in a web browser and is really the goal of what we want to do in order to create Java games. You can certainly write a Java game as an application and run it on a local system, but the real point of this book is to create Java applets that run in a web browser.

Java Applet

Now let’s create a Java applet and note how its code is different from a Java application. This applet that you’re about to write will run in a web browser, or you can run it with appletviewer.exe (one of the JDK tools). Open your favorite text editor (Notepad, TextPad, Emacs, or whichever it may be) and create a new file called FirstApplet.java with the following source code. TextPad is shown in Figure 1.6. Before you try to run the program, though, we’ll have to create a mini web page container, which we’ll create shortly.

The FirstApplet source code in TextPad.

Figure 1.6. The FirstApplet source code in TextPad.

Tip

The trial edition of TextPad has a pop-up that appears every time it is opened. You can register it at www.textpad.com for a small fee to get rid of the pop-up message, which will cause TextPad to start up much faster. I encourage you to support this developer if you find TextPad useful.

import java.awt.*;
import java.applet.*;
public class FirstApplet extends Applet {
    public void paint(Graphics g) {
        g.drawString("This is my first Java Applet!", 20, 30);
    }
}

The applet code is a little different from the application-based code in the DrinkJava program. Note the extends Applet code in the class definition and the lack of a static main method. An applet program extends a class called Applet, which means the applet will receive all of the features of the Applet class (which has the ability to run in a web browser). Essentially, all of the complexity of tying in your program with the web browser has been done for you through class inheritance (your program inherits the features of the Applet class). You can compile the program with this command:

javac FirstApplet.java

TextPad Configuration

Now, if you happen to be using TextPad (refer to Figure 1.6), you can compile the program from within TextPad without having to drop to the command prompt to compile it manually. As Figure 1.7 shows, TextPad has a macro that will launch the Java compiler for you and report the results of the compile. If there are no errors in the Java code, it will report “Tool completed successfully.”

Compiling Java code is a cinch in TextPad.

Figure 1.7. Compiling Java code is a cinch in TextPad.

If you don’t see the Java tools listed in this menu, then there’s a way to add them manually. Open the Configure menu and choose Preferences to bring up the Preferences dialog. The last item in the list of preferences is Tools. Select it. Click the Add button and choose “Java SDK Commands” from the list. This will add the Java tools to the list of external tools, as shown in Figure 1.8.

Adding the Java tools to the TextPad.

Figure 1.8. Adding the Java tools to the TextPad.

The next change is optional, but I think it’s helpful. Select the “Run Java Application” item under Tools, which was just added. There’s a check option called “Capture output,” as shown in Figure 1.9. Check this option. This will cause the Java output to go to the output window rather than causing a new window to open.

Configuring the Run Java Application tool.

Figure 1.9. Configuring the Run Java Application tool.

Figure 1.10 shows the change with the “Capture output” option enabled. Now, instead of TextPad bringing up a new window to show the Java program running, it displays the output directly in the Output window at the bottom of the TextPad window!

Java console output now goes to the Output window in TextPad.

Figure 1.10. Java console output now goes to the Output window in TextPad.

Applet Web Container

Java Applets can only run in a web browser or in the appletviewer. This is a basic web page containing the code to embed an applet on the page. We’ll be creating

one of these containers for every program in the book. But don’t worry, our development tools will generate the web container file for us. Here is what it looks like:

<html>
<head><title>FirstApplet</title></head>
<body>
<applet
  codebase = "."
  code = "FirstApplet.class"
  name = "FirstApplet"
  width = "640"
  height = "480"
  hspace = "0"
  vspace = "0"
  align = "middle"
>
</applet>
</body></html>

This container web page code includes an embedded <applet> tag with parameters that specify the Java applet class file and the width and height of the applet, among other properties. You can now open this file with Applet Viewer like so:

appletviewer FirstApplet.html

The Applet Viewer window appears with the FirstApplet program running, as shown in Figure 1.11.

The FirstApplet program is running inside the Applet Viewer utility.

Figure 1.11. The FirstApplet program is running inside the Applet Viewer utility.

You can also open the FirstApplet.html file in your favorite web browser. Using Windows Explorer, locate the folder containing your project and locate the FirstApplet.html file, then double-click it to open it in the default web browser. Figure 1.12 shows the applet running in Internet Explorer.

FirstApplet is running as an embedded applet in Internet Explorer.

Figure 1.12. FirstApplet is running as an embedded applet in Internet Explorer.

TextPad can generate the web container file for us! From the Tools menu, choose External Tools, then Run Java Applet. TextPad will automatically generate a web container file and launch it in AppletViewer, as shown in Figure 1.13.

Launching an applet from TextPad.

Figure 1.13. Launching an applet from TextPad.

Now that we’ve seen how to compile the program from the command line as well as from within the very simple to use editor, TextPad, we’ll look at how to compile a Java program with two major integrated development environments (IDEs): NetBeans and Eclipse.

Creating a NetBeans Project

NetBeans is a pretty good IDE, balancing features with usability without adding too much complexity. Let’s see how to create and configure a new Java Application project in NetBeans as a reference for all future projects. First, open the File menu and select New Project (see Figure 1.14).

Creating a new Java project in NetBeans.

Figure 1.14. Creating a new Java project in NetBeans.

The New Project dialog will appear (Figure 1.15). This dialog has many options and will look a bit different depending on the version of NetBeans that you have installed (this is the complete version with all tools installed). Choose the Java category in the list to the left, and Java Application from the list on the right.

The New Project dialog in NetBeans.

Figure 1.15. The New Project dialog in NetBeans.

A second project configuration dialog now comes up, titled New Java Application (Figure 1.16). Enter the new project name in the field. Unless you specifically want to change the location of the new project, the other options can be left alone.

The New Java Application project configuration dialog.

Figure 1.16. The New Java Application project configuration dialog.

At this point, the new project will be created with a sample source code file (Figure 1.17).

The new Java project has been created in NetBeans.

Figure 1.17. The new Java project has been created in NetBeans.

Add the following line of code to the main() function in the Main.java file. You can then run the project by pressing the F6 key or by opening the Run menu and selecting Run Main Project, as shown in Figure 1.18. The output is shown in the Output window at the bottom.

Compiling and running the project in NetBeans.

Figure 1.18. Compiling and running the project in NetBeans.

System.out.println("NetBeans makes Java programming easier!");

Creating an Eclipse Project

Eclipse is somewhat similar to NetBeans when it comes to creating a new project and running the Java code. There are a few extra steps that are a bit unusual, though, so a quick walkthrough is needed. This should help anyone who intends to use Eclipse for the projects in the book. First, open the File menu, choose New, Java Project, as shown in Figure 1.19.

Creating a new Java project in Eclipse.

Figure 1.19. Creating a new Java project in Eclipse.

This brings up the New Java Project dialog, shown in Figure 1.20. Enter the project name, choose the Java runtime to use (default shown here is JavaSE-1.6, as expected). One option I recommend setting is “Use project folder as root for sources and class files.” The other option will generate too many subfolders, making the project even more difficult to manage.

Setting the properties for a new Java project in Eclipse.

Figure 1.20. Setting the properties for a new Java project in Eclipse.

Eclipse does not use any project files to manage projects, but instead uses a workspace containing one or more project folders with source code files, such that no “file” is even related to the workspace—it’s just a bunch of folders containing sources. It’s definitely a different approach than the way most development tools work, and it can be difficult to use until you get the hang of working within a workspace. Note in Figure 1.21 that there are two “projects” listed in the Package Explorer. By default, a new project like the one we just created has no source code files—we have to add the first source file to the project.

Managing projects in an Eclipse workspace.

Figure 1.21. Managing projects in an Eclipse workspace.

Right-click on the project name in the Package Explorer, then choose New, Class, as shown in Figure 1.22.

Adding a new source file to the project.

Figure 1.22. Adding a new source file to the project.

The New Java Class dialog appears (Figure 1.23). Choose your desired source folder and enter a name such as “Main.” Be sure to check the option “public static void main(String[] args),” as this will generate our main function for us. If you don’t select the option, you’ll just have to type in extra code.

Adding a source file with the New Java Class dialog.

Figure 1.23. Adding a source file with the New Java Class dialog.

Now that the source file has been created, add this line to the main() function:

System.out.println("Doing Java in Eclipse. Yay!");

Run the program by clicking the green “Run” icon on the toolbar, as shown in Figure 1.24. The output is down at the bottom in the Console window.

Running our first Java program in Eclipse.

Figure 1.24. Running our first Java program in Eclipse.

JFrame-Powered Application

As mentioned earlier, JFrame makes it possible to do graphics in a Java application that is normally limited to just console output. JFrame provides a Graphics context, as does the Applet class, which can be used for drawing. The source code for a JFrame-based application is not any less code than an Applet project, but it foregoes the need of a web browser (or appletviewer), meaning we can run such a program with java.exe. The JFrameDemo project is shown in Figure 1.25, and the source code listing for the program follows. This is a bit more code than we’ve seen so far, but this program does more than any previous code.

The JFrameDemo project.

Figure 1.25. The JFrameDemo project.

package jframedemo;
import javax.swing.*;
import java.awt.*;
public class JFrameDemo extends JFrame
{
    public JFrameDemo()
    {
        super("JFrameDemo");
        setSize(400,400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void paint(Graphics g)
    {
        super.paint(g);
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 400, 400);
        g.setColor(Color.orange);
        g.setFont(new Font("Arial", Font.BOLD, 18));
        g.drawString("Doing graphics with a JFrame!", 60, 200);
    }
    public static void main(String[] args)
    {
        new JFrameDemo();
    }
}

Let’s go over this code. It’s important to understand this basic code because all of our game projects coming up will be based on the code you see here—extending JFrame, with a main() method, a paint() method, and a constructor.

First, we need javax.swing, which owns the JFrame class, while java.awt makes the Graphics class available. The JFrameDemo class is the main class of the program, which extends JFrame, meaning that our class is a JFrame. There are some things that come with a JFrame class, such as the paint() method, which renders the window when the program first starts up. We still need our main() function, and it has a single purpose: to launch the JFrame-powered class, JFrameDemo. The JFrameDemo() method is actually the constructor for the class, meaning it runs when the class is first created. Anything you want to happen when the window is first created and comes up, you could put in the constructor. So, we set the window title, the dimensions, and other useful properties. Figure 1.26 shows the output.

A JFrame window with a Graphics context for drawing.

Figure 1.26. A JFrame window with a Graphics context for drawing.

What You Have Learned

Well, this has been a pretty heavy chapter that covered a lot of introductory information about working with several Java development tools, but the goal was to get the basics covered so that we can jump right into Java game programming in the next chapter. Consider this a reference chapter on creating Java projects with the various development tools, and come back here any time you need to create a new project but can’t quite remember all of the steps. You learned about:

  • Casual games, what they are, and their importance

  • The Java Development Kit (JDK) and Java versions

  • Editing and compiling Java code

  • Standalone Java applications and Java applets

  • Using Eclipse, NetBeans, and TextPad

Review Questions

The following questions will help you to determine how well you have learned the subjects discussed in this chapter. The answers are provided in Appendix A, “Chapter Quiz Answers.”

1.

What does the acronym “JDK” stand for?

2.

What version of the JDK are we focusing on in this book?

3.

What is the name of the company that created Java?

4.

Where on the web will you find the text editor called TextPad?

5.

In what year was Java first released?

6.

Where on the web is the primary download site for Java?

7.

What type of Java program do you run with the java.exe tool?

8.

What type of Java program runs in a web browser?

9.

What is the name of the command-line tool used to run a web-based Java program?

10.

What is the name of the parameter passed to the paint() event method in an applet?

On Your Own

Use the following exercises to test your grasp of the material covered in this chapter.

Exercise 1

Modify the FirstApplet program so that it displays your own message on the screen below the current message.

Exercise 2

The JFrame Demo program displayed a message with orange text over a white background. See if you can change the background color to black and the text color to green.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.206.244