You can program in Java (or are learning to.) That's great! But what else can you do with those skills? Are you trapped with Java?
Not at all. One of the reasons I chose Java as a language for use in the classroom is that Java programming skills translate so well into skills for other languages. Here are some other languages, and a brief look at what your Java programming skills will give you in the way of a head start, and what differences to look out for.
C# (C Sharp)
C# and Java are practically the same. C#'s roots are in Java, as is the concept of its libraries relative to Java's API. The libraries differ, but if you're used to Java's API you'll have no trouble getting right into C#'s libraries to find the classes you're looking for.
The major development tools are very similar, or, in many cases, you can use the same IDEs for C# as for Java. You can also do cross-platform development in C# just as you can with Java thanks to tools like Mono (which I highly recommend as a way of becoming familiar with C#) and the forthcoming cross-platform Visual Studio tools from Microsoft.
C
Java is an object-oriented descendent from the C language. C does not have object-orientation built in, but you should have no trouble understanding much of the code. Imagine writing Java without creating your own classes, or only creating limited classes. This isn't strictly accurate, since it is possible to write object-oriented code in C, it just requires the programmer to do much of the work that Java does in their code. Providing for isolation of data, inheritance, etc. has to be performed through code written explicitly to perform these functions.
Modern versions of C, such as ANSI C/ISO C (C99) provide a version of C which makes it easier to write good code if you're coming from an object-oriented background.
Another major hurdle will be dealing with memory management directly (C has no garbage collection), and learning how to use the various functions of C which are often not as predictable as the Java methods you are familiar with.
The basics of C will already be familiar to you, but you should conduct some formal study of C and use its standard libraries extensively before seeking to start formal projects with it.
C++
C++ is another object-oriented outgrowth of C, like Java, yet it uses a very different approach. You will find that your Java experience can be very misleading with respect to the handling of data and the operation of methods in C++. Also, C++'s libraries tend to be much more platform-specific than those of Java. In Java you have platform-specific libraries, yet it is possible to write good code that does not rely on it, or that relies on it little enough to allow 90% or more of your code to be written in a non-platform-specific fashion.
With C++, however, you'll find that while there are standard cross-platform libraries, most code will be best written to the platform to which it is being compiled.
Python
Python will be very easy to learn once you know Java. Its syntax is quite different, and its approach to what is implicit and what must be explicitly defined is very different to that of Java. Conceptually, however, you will be right at home and will be able to learn the specifics of the language very easily.
Like Java, Python has extensive libraries. Some are part of Python's core distribution, but others are not. You will find that even in the core libraries there is much less cross-platform support than Python seems to promise. Also, you will need platform-specific libraries for any graphics or audio code. Even in cross-platform libraries, you will find that there are significant differences between platforms. If you are writing code that does not rely on the platform for presentation, however, (for example code that uses a browser), Python works very well in a cross-platform environment.
Javascript
Javascript is also very similar to Java in many ways, but not as much as the name of the language might lead you to believe. Java has recently acquired many of the constructs that have been favorites of Javascript programmers for years.
You will find that handling data under Javascript is very different to the means used in Java. You will also find the nomenclature very, very different, despite the similarities in the languages. This will probably be your biggest early hurdle in transitioning from one language to the other.
The best approach is to set yourself to learn the ways that things are best done in Javascript, before trying to write Java code in Javascript syntax. Once you can write solid small programs, enough will become apparent to you that you can begin to take advantage of your programming knowledge from Java to apply it to your Javascript programs. Some programming languages it is your knowledge of Java syntax and structure that will make those languages easy for you. Javascript isn't one of those languages. The payoff comes after you have learned Javascript syntax and structure, the process of designing well-build object oriented software will pay off.
With Javascript, the web browser is almost certain to be your "platform." You will need to learn the Domain Object Model to effectively apply Javascript. If you have already been using the DOM with your Java code (over half of Java code is written for the web), then you are already there. Otherwise, it's something else new you'll have to learn.
Objective-C
The transition from Java to Objective-C is far simpler than to C++. The object-oriented techniques used in Objective-C will make immediate sense to a Java programmer, as will the program structure. Objective-C requires you to do your own memory management, unlike Java, but it provides facilities to do so more simply and effectively than standard C.
The libraries will differ completely from those of Java, and your platform will almost certainly be iOS or Macintosh, so those are the platforms whose libraries you'll learn. Objective-C differs from Java more than C#, but not so much as to make it extremely difficult to transition to. After C#, Objective-C is probably the easiest non-scripting language for you to learn.
Swift
Swift is based on Objective-C, and will be even easier for a Java programmer to learn and use. Most of the changes not only make it easier to produce programs in general, but make it conceptually simpler for a Java programmer to make the transition. You'll be reading the code in the first day, and will be able to produce effective code with only a few hours of work. As with Objective-C, there are new libraries for you to learn tied to Swift's platforms (iOS and Mac), but you will find these even easier to navigate than the Java libraries that suffer from Java's early history of development being encased within them.
PHP
PHP does not have the sort of object-oriented programming facilities that you will be used to from Java, but its syntax will be easy for you to pick up. You will likely feel limited by PHP compared to Java, but PHP has a more limited purpose than Java--it is focused on web programming. While Java is heavily used for server-side web programming, it is much more of a general purpose language than PHP.
You will need to learn the specifics of PHP's syntax and data structures, but after mastering Java, you will not find this difficult.
Summary
These cover the most popular programming languages in use at this time. There are other languages, like Scala, that are specifically designed to be like Java yet address shortcomings perceived in Java, either for some specific use, or to change things that are historically embedded in Java's design. These are very easy for a Java programmer to transition to.
At present, Oracle's support of Java is limiting its market relative to the general use for Java that Sun used to promote. While Java is still widely used, and will continue to be for the foreseeable future, it always behooves a programmer to be competent in multiple languages and to have more than one set of conceptual tools for problem solving at hand. So it is good to know other languages, even if they are scripting languages like Python and Ruby.
Currently, Microsoft is in the process of making a strong play to the cross-platform development market which Java has served. With C# as part of this, and C# plus Mono (a cross-platform version of .Net) already available, it is very easy for a Java programmer to add this to their programming portfolio to gain a greater range of opportunities for work, and a wider range of tools for solving programming problems.
I highly recommend, at least, spending some time with C# under Mono or .Net if you are currently a Java programmer. I think you'll find that you feel right at home.
An advantage of learning .Net is that it will open up Windows-specific programming in C++ to you as well. The C++ language will be new, but you'll already know the libraries that you'll be using. If Microsoft delivers on their recent promises of making their tools fully cross-platform for Mac and Linux, then you'll be able to apply those skills to those platforms as well.
Mobile
Java is the language you'll use on Android, currently the dominant mobile platform in terms of users. Objective-C is the language for iOS, and it's not a huge jump for a Java programmer to make. Swift is a simplified version of Objective-C, and it is even easier for the Java programmer to learn. If you are planning to develop for iOS, it is worth making the effort to transition to a language built for it, and Swift should be your first stop.
Showing posts with label API. Show all posts
Showing posts with label API. Show all posts
Monday, November 17, 2014
Portability of Java Programming Skills
Labels:
Android,
API,
application,
C,
C#,
C++,
cross-platform,
environment,
graphics,
IDE,
Java,
Javascript,
PHP,
Swift,
web,
why java

Tuesday, November 12, 2013
DozCalc: A More Polished Android Application in Java
Since my post on my first Android app, I've done a lot. I went on from that first app to learn how to access a lot more of the device, deal with a wider range of circumstances, and generally get to know Android and the tools for developing for it better.
Specifically, I have posted an app for Android called DozCalc.
DozCalc is a dozenal (base 12) calculator. It doesn't convert back and forth between dozenal and decimal, so be warned. Just like your normal four function calculator that works in base 10 and nothing else, DozCalc works in base 12 and nothing else.
Java
The "programming", like development in many modern GUI environments, was less about the functional code (in this case in Java) and more about the user interface. While Android allows for UI programming in Java, it's typically simpler to implement it in XML. And this is what I did.
The only problem I had was dealing with loss of precision in some calculations. At first, I was going to be very clever and write a proper function using numerical analysis to get the value right to some specified number of fractional digits (note: it's not proper to call them 'decimal digits' when you're working strictly in base 12). However, it was simpler and easier to just add a small value to certain calculations (division, for example) to make all the fractional values come out correct. Far simpler to program, just as effective for this use, and every bit as accurate as the average four function calculator.
Sometimes programming is less about the language, or the algorithm, than about just getting a solution that's accurate enough for the need, then moving forward.
Thanks to object-oriented design, I was able to re-use the code from DozCalc in another graphical calculator. Unfortunately, I got bogged down in the graphical design, so the steampunk styled version of DozCalc (named Mr Wells' Calculator) has yet to be released, and may not be depending on how my schedule of current projects goes.
Specifically, I have posted an app for Android called DozCalc.
DozCalc is a dozenal (base 12) calculator. It doesn't convert back and forth between dozenal and decimal, so be warned. Just like your normal four function calculator that works in base 10 and nothing else, DozCalc works in base 12 and nothing else.
Java
The "programming", like development in many modern GUI environments, was less about the functional code (in this case in Java) and more about the user interface. While Android allows for UI programming in Java, it's typically simpler to implement it in XML. And this is what I did.
The only problem I had was dealing with loss of precision in some calculations. At first, I was going to be very clever and write a proper function using numerical analysis to get the value right to some specified number of fractional digits (note: it's not proper to call them 'decimal digits' when you're working strictly in base 12). However, it was simpler and easier to just add a small value to certain calculations (division, for example) to make all the fractional values come out correct. Far simpler to program, just as effective for this use, and every bit as accurate as the average four function calculator.
Sometimes programming is less about the language, or the algorithm, than about just getting a solution that's accurate enough for the need, then moving forward.
Thanks to object-oriented design, I was able to re-use the code from DozCalc in another graphical calculator. Unfortunately, I got bogged down in the graphical design, so the steampunk styled version of DozCalc (named Mr Wells' Calculator) has yet to be released, and may not be depending on how my schedule of current projects goes.
Labels:
Android,
API,
application,
calculations,
Java,
JVM,
operators,
why java

Sunday, January 13, 2013
My First Android App
I ordered an Android phone about two weeks ago.
Last Thursday, I installed the Android SDK. It went smoothly, I've installed it under two versions of Windows 7, as those are my systems with the most RAM and CPU power (for the Android device emulator. My older Mac and Linux systems lug a bit when doing serious hardware emulation.)
I started the online tutorials linked on the SDK's opening page. Since the SDK is based on Eclipse (my favorite full-fat IDE for Java), it was no problem getting started.
I got a simple app, modified from the 'getting started' tutorial, running on an emulated Android device within an hour or so of starting.
The next day--Friday, my phone arrived in the mail. It runs Android 4.1.1.
After a busy day on Friday interleaved with charging and moving into the phone, I got the Android SDK talking to my phone today, downloaded an updated version of the app (a =very= simple character generator for my RPG, RoonVenture.) It ran just fine. It's very similar to my online RoonVenture Character Generator.
That is, it's ugly, poorly designed, but bone-simple while producing the essential results.
Nevertheless, I found my Java skills played right into Android development (so far):
Android's native language is Java, with some unique libraries.
The default IDE is Eclipse, a common Java IDE (and one I recommend, though I still do about half my code in something lighter, ranging from vi or vim to Arachnophilia or BlueJ.)
It's a lot like Java ME development (which I've done to build apps for my older "feature phones".)
So, if you're doing Java now, I recommend jumping into Android if the opportunity arises. I've found it easier to get started than with Java ME, Blackberry, or Nokia Series 60 development. Though it's worth noting that I'm coming to this with prior experience with all of those first.
Now I'm taking a break from the computer and reading a hardcopy book, "Creating Android Applications" by Chris Haseman. It's written for the experienced Java programmer who doesn't need 250 pages on Java and Eclipse.
That should help me make a better app next. :)
Last Thursday, I installed the Android SDK. It went smoothly, I've installed it under two versions of Windows 7, as those are my systems with the most RAM and CPU power (for the Android device emulator. My older Mac and Linux systems lug a bit when doing serious hardware emulation.)
I started the online tutorials linked on the SDK's opening page. Since the SDK is based on Eclipse (my favorite full-fat IDE for Java), it was no problem getting started.
I got a simple app, modified from the 'getting started' tutorial, running on an emulated Android device within an hour or so of starting.
The next day--Friday, my phone arrived in the mail. It runs Android 4.1.1.
After a busy day on Friday interleaved with charging and moving into the phone, I got the Android SDK talking to my phone today, downloaded an updated version of the app (a =very= simple character generator for my RPG, RoonVenture.) It ran just fine. It's very similar to my online RoonVenture Character Generator.
That is, it's ugly, poorly designed, but bone-simple while producing the essential results.
Nevertheless, I found my Java skills played right into Android development (so far):
Android's native language is Java, with some unique libraries.
The default IDE is Eclipse, a common Java IDE (and one I recommend, though I still do about half my code in something lighter, ranging from vi or vim to Arachnophilia or BlueJ.)
It's a lot like Java ME development (which I've done to build apps for my older "feature phones".)
So, if you're doing Java now, I recommend jumping into Android if the opportunity arises. I've found it easier to get started than with Java ME, Blackberry, or Nokia Series 60 development. Though it's worth noting that I'm coming to this with prior experience with all of those first.
Now I'm taking a break from the computer and reading a hardcopy book, "Creating Android Applications" by Chris Haseman. It's written for the experienced Java programmer who doesn't need 250 pages on Java and Eclipse.
That should help me make a better app next. :)

Tuesday, June 7, 2011
Doing Math in Java part 2:Functions
The basics of math in Java using operators was covered in Part 1: Operators. There I went over the standard operations built into the language itself, rather than in its APIs (libraries).
But that's hardly the end of useful math operations. Especially when doing graphics, where all those geometric and trigonometric functions come in so useful. Square root, cosine, absolute values, etc.
If you're wandering into the Java APIs unguided, the java.math package might catch your eye right away. Unfortunately, it's a false trail when what you're looking for is a simple general purpose math package (it's a nice special-purpose math package for particular sorts of calculation, however.)
What you really want is the java.lang.Math class, in the java.lang package.
This has most of the standard math functions you're used to. They're defined as static methods, so you don't need to create a Math object to use them. You just call them like this:
These call the square root function
Date Calculations
Calculations with dates are another standard sort of math that's not covered by standard operators. In the package java.util we've got the Calendar class. The Calendar class itself is an abstract class. This means that it's a class used to build other classes with, not to use directly. The GregorianCalendar class is a concrete implementation of
Example:
Unfortunately, the Calendar class demonstrates one of the problems with much of Java. It's an overly generalized class that prevents simple solutions to many simple and obvious problems. The older Date class took a more direct approach, but it has been deprecated in favor of the Calendar based classes. Unfortunately, even obtaining a printable date value according to the system's current locale takes a fair bit of set up in Java. A better solution would have been a very general class like Calendar behind a more usable class for solving conventional problems, but Java's development got it backward. We got the simple class first, it's inflexibility for solving certain problems resulted in criticism, then came a general class, which is no good at doing simple and obvious things for most users. The extra layer that we should have to make Calendar more usable has not yet appeared in the standard API (and possibly never will.)
So it takes a lot of code to do what should only take a line or two, when working with dates.
Still, give the Calendar and GregorianCalendar class a look-over. Even though it takes some extra code and set-up to do some simple tasks, the solutions to these problems are well established and many examples are available. It's just not as simple as System.out.println(myDate);
I'll be adding articles dealing specifically with dates myself at a future date.
But that's hardly the end of useful math operations. Especially when doing graphics, where all those geometric and trigonometric functions come in so useful. Square root, cosine, absolute values, etc.
If you're wandering into the Java APIs unguided, the java.math package might catch your eye right away. Unfortunately, it's a false trail when what you're looking for is a simple general purpose math package (it's a nice special-purpose math package for particular sorts of calculation, however.)
What you really want is the java.lang.Math class, in the java.lang package.
This has most of the standard math functions you're used to. They're defined as static methods, so you don't need to create a Math object to use them. You just call them like this:
float distance = Math.sqrt(dx*dx + dy*dy);
float speed = Math.abs(velocity);
These call the square root function
Math.sqrt()
and absolute value function Math.abs()
. There are a slew of others like degree to radian conversion, the standard trig functions, and so on.Date Calculations
Calculations with dates are another standard sort of math that's not covered by standard operators. In the package java.util we've got the Calendar class. The Calendar class itself is an abstract class. This means that it's a class used to build other classes with, not to use directly. The GregorianCalendar class is a concrete implementation of
Calendar
that you can use directly. The Calendar object's add() method will add or subtract some amount of time--days, minutes, hours, etc.--to or from a given date (the date that the object is set to:- Create a GregorianCalendar Object
- Set its date
- Use its add() method to add or subtract the time difference.
Example:
GregorianCalendar myDate;
myDate = new GregorianCalendar(2011, 6, 7); //set the date to 07 June 2011.
myDate.add(Calendar.Date, 165); // add 165 days to that date.
before()
, after()
and compareTo
will return whether one date occurs before or after another. Computing the number of days between two dates is a bit more complex, unfortunately, as are similar calculations. Basically, the procedure is to use getTime() to convert both dates to time values, get the difference, then divide that by the time units you want to see the difference in (e.g. divide by 24 hours periods to get the difference in days.)Unfortunately, the Calendar class demonstrates one of the problems with much of Java. It's an overly generalized class that prevents simple solutions to many simple and obvious problems. The older Date class took a more direct approach, but it has been deprecated in favor of the Calendar based classes. Unfortunately, even obtaining a printable date value according to the system's current locale takes a fair bit of set up in Java. A better solution would have been a very general class like Calendar behind a more usable class for solving conventional problems, but Java's development got it backward. We got the simple class first, it's inflexibility for solving certain problems resulted in criticism, then came a general class, which is no good at doing simple and obvious things for most users. The extra layer that we should have to make Calendar more usable has not yet appeared in the standard API (and possibly never will.)
So it takes a lot of code to do what should only take a line or two, when working with dates.
Still, give the Calendar and GregorianCalendar class a look-over. Even though it takes some extra code and set-up to do some simple tasks, the solutions to these problems are well established and many examples are available. It's just not as simple as System.out.println(myDate);
I'll be adding articles dealing specifically with dates myself at a future date.
Labels:
API,
calculations,
dates,
Java,
Math,
methods,
trigonometry

Tuesday, August 24, 2010
Using Game Controllers with Java
In the past, I've covered using mice as input devices, and covered the general input mechanism of Listeners. I've also discussed keyboard input for console applications, and I'll soon be covering Key Bindings as a way of using the keyboard in GUI applications.
But there's no facility in Java itself that deals with game pads easily. To date, it's been necessary to create your own ActionListeners from scratch. But not any more. Thanks to the JInput project, there's an easier way to hook up game controllers to your software.
JInput attempts to do discovery on your game controller, to figure out what its setting are, what buttons and controls it has, what the center positions are of analog sticks, and so on. All that messy stuff that makes rolling your own so darn painful. It's not 100% universal, but for most controllers and most games, it will do the job admirably. If you want better for a specific controller of your own, you can extend the classes to handle your stick (and maybe feed that information back to the JInput team so that they can decide whether to include it in future releases.
It's multi-platform, Windows, Mac OS X, and Linux. So it doesn't have the limitations of a lot of the other gamepad code implementations that use native code, thus limiting themselves to one platform (usually Windows.)
If you want to see an implementation using JInput, check out Greenfoot with Gamepads. It's a good, clear example of using JInput in a general fashion.
But there's no facility in Java itself that deals with game pads easily. To date, it's been necessary to create your own ActionListeners from scratch. But not any more. Thanks to the JInput project, there's an easier way to hook up game controllers to your software.
JInput attempts to do discovery on your game controller, to figure out what its setting are, what buttons and controls it has, what the center positions are of analog sticks, and so on. All that messy stuff that makes rolling your own so darn painful. It's not 100% universal, but for most controllers and most games, it will do the job admirably. If you want better for a specific controller of your own, you can extend the classes to handle your stick (and maybe feed that information back to the JInput team so that they can decide whether to include it in future releases.
It's multi-platform, Windows, Mac OS X, and Linux. So it doesn't have the limitations of a lot of the other gamepad code implementations that use native code, thus limiting themselves to one platform (usually Windows.)
If you want to see an implementation using JInput, check out Greenfoot with Gamepads. It's a good, clear example of using JInput in a general fashion.

Friday, August 14, 2009
Java 3D Graphics Options
There are several approaches to doing 3-D graphics with Java. Unfortunately, there is no "standard" way. The core of Java does not include 3D graphics in the current versions (Java SE 5 and 6). The upcoming new version (SE 7) also does not, though it is intended to include a modular system that will download Java components that aren't already on a system as they are required. Chances are the major Java 3D APIs will take advantage of this.
Ways to Get 3-D Graphics in a Java Program:
1. Code It Yourself
You can write your own 3D graphics routines in standard Java. This avoids the need for those who run your programs to get add-ons to their Java to run your programs. It also means you'll really know what's going on in your 3D code.
However, this probably won't be an effective technique for you if you want to write programs with very sophisticated 3D in them, or need high performance.
2. JOGL
JOGL is a low-level set of APIs for accessing OpenGL on the system the program is running on. Runescape uses it. If you want to learn how to program 3-D the way most of the pros do it, and aren't afraid of having to learn all sorts of technical 3D graphics stuff to get there, then JOGL may be for you.
If you want to stick to a Java-like object oriented way of thinking, or don't want to delve too deeply into the underlying 3D graphics technology just to get a picture on-screen, then JOGL is probably not for you.
3. LWJGL
Another acronym, another low-level library like JOGL. LWJGL is oriented toward game development, including support for hardware like gamepads and controllers in addition to 3D graphics support. With respect to graphics, it has the same advantages and disadvantages as JOGL.
If I were going to start using the other capabilities of LWJGL right away, I'd start with it rather than JOGL. If I were focused on learning 3D graphics programming with OpenGL first, for example using the "Red Book" for OpenGL, I'd start with JOGL then move over to LWJGL if I felt it would be helpful.
4. Java3D
This is a high-level Java API that uses an object-oriented way of doing 3D graphics. It sticks with the same approach to doing things as the rest of Java. It lets you easily create 3D objects and set them up in scenes for display. If you're entirely new to 3D this is probably the place to start learning.
To use it, you need to install it on your system. Also, anyone who wants to run your Java3D programs will need to have it, too.
Java 3D binaries for different computer systems are available for download.
A good community site for further information on doing 3-D graphics with Java--no matter how you want to do them--is j3d.org.
Ways to Get 3-D Graphics in a Java Program:
1. Code It Yourself
You can write your own 3D graphics routines in standard Java. This avoids the need for those who run your programs to get add-ons to their Java to run your programs. It also means you'll really know what's going on in your 3D code.
However, this probably won't be an effective technique for you if you want to write programs with very sophisticated 3D in them, or need high performance.
2. JOGL
JOGL is a low-level set of APIs for accessing OpenGL on the system the program is running on. Runescape uses it. If you want to learn how to program 3-D the way most of the pros do it, and aren't afraid of having to learn all sorts of technical 3D graphics stuff to get there, then JOGL may be for you.
If you want to stick to a Java-like object oriented way of thinking, or don't want to delve too deeply into the underlying 3D graphics technology just to get a picture on-screen, then JOGL is probably not for you.
3. LWJGL
Another acronym, another low-level library like JOGL. LWJGL is oriented toward game development, including support for hardware like gamepads and controllers in addition to 3D graphics support. With respect to graphics, it has the same advantages and disadvantages as JOGL.
If I were going to start using the other capabilities of LWJGL right away, I'd start with it rather than JOGL. If I were focused on learning 3D graphics programming with OpenGL first, for example using the "Red Book" for OpenGL, I'd start with JOGL then move over to LWJGL if I felt it would be helpful.
4. Java3D
This is a high-level Java API that uses an object-oriented way of doing 3D graphics. It sticks with the same approach to doing things as the rest of Java. It lets you easily create 3D objects and set them up in scenes for display. If you're entirely new to 3D this is probably the place to start learning.
To use it, you need to install it on your system. Also, anyone who wants to run your Java3D programs will need to have it, too.
Java 3D binaries for different computer systems are available for download.
A good community site for further information on doing 3-D graphics with Java--no matter how you want to do them--is j3d.org.
Labels:
API,
graphics,
Java version

Friday, February 20, 2009
Rotating an Image with Java
In an earlier lesson we learned to load an image file into Java and display it. We also scaled the image in the program given in that lesson. Now we're going to get just a tiny bit more sophisticated, and rotate the image, as promised in the lesson introducing Java2D.
The basic graphics functions of Java allow for positioning an image in a window and scaling that image. But that's about all. If you want to rotate the image, skew it (make it look like it's leaning over) or do other things to the image you display you need to use Java2D.
What we'll do in this program is load the image as before. But before the image is drawn we will create a Java2D version of our graphics object that we're drawing to. Then we'll rotate that graphics object and draw the image. The rotation results in everything that gets drawn to the graphics area being rotated by the amount specified.
The program uses the same image of Duke as the previous one. It needs to be in the same directory as your program.
Here's the program. More discussion of the program follows the listing.
Most of this program is the same as our previous one. There are a couple of significant changes, however.
One is the following line:
In this line we're doing what's known as a "cast". We're declaring a new Graphics2D object, naming it g2d, then setting its value to our present Graphics object, g. But since g is a Graphics object, and not a Graphics2D object, we're telling it to treat g as a Graphics2D object for the purposes of this assignment. We can get away with doing this because Graphics2D is a subclass of Graphics, which makes the two classes compatible enough to allow the cast to be successful.
By doing this, we "magically" make all the Graphics2D functions available for drawing to our window.
What we want to do is rotate our image. Since we don't want to have the image go outside our graphics area when we rotate it, I've moved our "point of origin" of our graphics area using
This moves the center point around which the drawing area is rotated from the upper left corner of the window's display area to a point 170 pixels to the right of that.
Then we use the rotate() method of our Graphics2D object, which will cause everything drawn into it to be rotated:
The amount we're rotating is 1 radian, or about 57 degrees, noted by the 1 inside the parentheses.
Then we use the drawImage method of our Graphics2D object to actually draw the image into our display area.
Experiment with different values for the rotate() method to see rotation at different angles. If you lose part of the image off the edge of the window, try to use different offsets in the drawImage() method to change the location within the window at which the image gets drawn.
This is a fairly simple method for rotating an image in Java. It has some value for creating static images that are rotated, but for something like sprites in a game it's not very useful. The best method for that would be to create rotated images in a graphics program, not in your Java program. It's possible to rotate your images in Java, but it gets complicated because you have to worry about a lot of things that your graphics program does for you, like the area your new image will fill relative to the original, the background of the image, and so on.
Once you have image files of your sprite in all its possible rotated angles, load all these images to different Image object in a Java program (or better yet, an Image array or Collection), and change between them to show the image rotating.
The basic graphics functions of Java allow for positioning an image in a window and scaling that image. But that's about all. If you want to rotate the image, skew it (make it look like it's leaning over) or do other things to the image you display you need to use Java2D.
What we'll do in this program is load the image as before. But before the image is drawn we will create a Java2D version of our graphics object that we're drawing to. Then we'll rotate that graphics object and draw the image. The rotation results in everything that gets drawn to the graphics area being rotated by the amount specified.
The program uses the same image of Duke as the previous one. It needs to be in the same directory as your program.
Here's the program. More discussion of the program follows the listing.
// Import the basic graphics classes./**
import java.awt.*;
import javax.swing.*;
* Simple program that loads, rotates and displays an image.
* Uses the file Duke_Blocks.gif, which should be in
* the same directory.
*
* @author MAG
* @version 20Feb2009
*/
public class RotateImage extends JPanel{
// Declare an Image object for us to use.
Image image;
// Create a constructor method
public RotateImage(){
super();
// Load an image to play with.
image = Toolkit.getDefaultToolkit().getImage("Duke_Blocks.gif");
}
public void paintComponent(Graphics g){
Graphics2D g2d=(Graphics2D)g; // Create a Java2D version of g.
g2d.translate(170, 0); // Translate the center of our coordinates.
g2d.rotate(1); // Rotate the image by 1 radian.
g2d.drawImage(image, 0, 0, 200, 200, this);
}
public static void main(String arg[]){
JFrame frame = new JFrame("RotateImage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,400);
RotateImage panel = new RotateImage();
frame.setContentPane(panel);
frame.setVisible(true);
}
}
Most of this program is the same as our previous one. There are a couple of significant changes, however.
One is the following line:
Graphics2D g2d=(Graphics2D)g;
In this line we're doing what's known as a "cast". We're declaring a new Graphics2D object, naming it g2d, then setting its value to our present Graphics object, g. But since g is a Graphics object, and not a Graphics2D object, we're telling it to treat g as a Graphics2D object for the purposes of this assignment. We can get away with doing this because Graphics2D is a subclass of Graphics, which makes the two classes compatible enough to allow the cast to be successful.
By doing this, we "magically" make all the Graphics2D functions available for drawing to our window.
What we want to do is rotate our image. Since we don't want to have the image go outside our graphics area when we rotate it, I've moved our "point of origin" of our graphics area using
g2d.translate(170, 0);
This moves the center point around which the drawing area is rotated from the upper left corner of the window's display area to a point 170 pixels to the right of that.
Then we use the rotate() method of our Graphics2D object, which will cause everything drawn into it to be rotated:
g2d.rotate(1);
The amount we're rotating is 1 radian, or about 57 degrees, noted by the 1 inside the parentheses.
Then we use the drawImage method of our Graphics2D object to actually draw the image into our display area.
Experiment with different values for the rotate() method to see rotation at different angles. If you lose part of the image off the edge of the window, try to use different offsets in the drawImage() method to change the location within the window at which the image gets drawn.
This is a fairly simple method for rotating an image in Java. It has some value for creating static images that are rotated, but for something like sprites in a game it's not very useful. The best method for that would be to create rotated images in a graphics program, not in your Java program. It's possible to rotate your images in Java, but it gets complicated because you have to worry about a lot of things that your graphics program does for you, like the area your new image will fill relative to the original, the background of the image, and so on.
Once you have image files of your sprite in all its possible rotated angles, load all these images to different Image object in a Java program (or better yet, an Image array or Collection), and change between them to show the image rotating.

Saturday, February 14, 2009
Better 2D Graphics: Java2D
In our last program we loaded and displayed an image using Java. Not only that, but we scaled it to be a specific size. We did this using the Image class from the java.awt package.
Unfortunately, this pretty well covers the abilities of the Image class. But there's so much more that we'd like to do with images in our programs, especially if we're writing games. Fortunately, there's more that Java can do with images thanks to Java2D.
If you go to the Java API you won't see a specific package called something like java.java2d or javax.swing.java2d. "Java2D" is a whole bunch of packages and classes spread through Java's libraries of stuff. The java.awt.image package is part of Java2D, as is the java.awt.Graphics2D class inside the java.awt package. For a list of all the scattered components of Java that are part of Java2D, have a look at the Java2D API Specification.
Like so much of Java, the presentation of Java2D is confusing. It's made to sound like a single thing when it's a bunch of interrelated things worked into Java. Fortunately, like many such problems in understanding Java, it's only a problem of how the language is presented, not a problem with the language itself. Once you get to working with the elements of Java2D, you find that they're fairly naturally positioned in the places you would expect them in Java by their function. Which is how they got spread out in the first place (that and some history--it would have been even more natural to have there be one Graphics class that does everything, rather than a Graphics and Graphics2D class.)
Also, it's very easy to take items that are non-Java2D classes and use them with Java2D. Usually it's nothing worse than "casting" them as Java2D objects. That means you basically tell Java "pretend this object is the right sort of thing" in a way that works.
So have a look at some info on Java2D, and if it looks confusing, remember it's not you that's the problem. Sun does an amazing job of presenting great things in awful ways by trying to say way too much to too many different audiences at once. And they like to start in the middle of the story.
The Java2D tutorials do a decent job of showing things off without a lot of mind-numbing prose (well, not too much, anyway.)
Next I'll post a short, simple program we can use that rotates our images.
Unfortunately, this pretty well covers the abilities of the Image class. But there's so much more that we'd like to do with images in our programs, especially if we're writing games. Fortunately, there's more that Java can do with images thanks to Java2D.
If you go to the Java API you won't see a specific package called something like java.java2d or javax.swing.java2d. "Java2D" is a whole bunch of packages and classes spread through Java's libraries of stuff. The java.awt.image package is part of Java2D, as is the java.awt.Graphics2D class inside the java.awt package. For a list of all the scattered components of Java that are part of Java2D, have a look at the Java2D API Specification.
Like so much of Java, the presentation of Java2D is confusing. It's made to sound like a single thing when it's a bunch of interrelated things worked into Java. Fortunately, like many such problems in understanding Java, it's only a problem of how the language is presented, not a problem with the language itself. Once you get to working with the elements of Java2D, you find that they're fairly naturally positioned in the places you would expect them in Java by their function. Which is how they got spread out in the first place (that and some history--it would have been even more natural to have there be one Graphics class that does everything, rather than a Graphics and Graphics2D class.)
Also, it's very easy to take items that are non-Java2D classes and use them with Java2D. Usually it's nothing worse than "casting" them as Java2D objects. That means you basically tell Java "pretend this object is the right sort of thing" in a way that works.
So have a look at some info on Java2D, and if it looks confusing, remember it's not you that's the problem. Sun does an amazing job of presenting great things in awful ways by trying to say way too much to too many different audiences at once. And they like to start in the middle of the story.
The Java2D tutorials do a decent job of showing things off without a lot of mind-numbing prose (well, not too much, anyway.)
Next I'll post a short, simple program we can use that rotates our images.

Tuesday, January 13, 2009
Listeners: Can Java Hear You?
In the program given in Simple Mouse Interaction in Java we used a Listener to connect our program to the mouse. We were able to use the Listener to find out when and where the mouse had been clicked within our program's window. We used this information to draw lines in the window, in a similar fashion to our earlier programs but controlled by the mouse, rather than from specific drawing instructions in the program that do the same thing every time you run the program.
By implementing the MouseListener interface, we were able to talk to the mouse very easily. However, a MouseListener is just one of the many types of Listener available in Java.
What Sort of Listener Are You?
If we tried to implement a full graphical interface in a program by using MouseListener, we'd have a lot of work to do. We'd have to draw all the buttons using drawing instructions in our program, then wait for mouse clicks. Once we got a click on something we'd have to figure out what had been clicked on by the location of the click in our window. Then we'd have to redraw the button (or slider, or whatever) to show that it had been clicked. Then we'd have to continue responding to the mouse by figuring out what the user is doing (clicking and releasing, clicking and dragging, or what) and make our program and the picture on the screen respond appropriately.
Whew! What a lot of work that would be! If we had to do that it'd almost be enough to drive you back to the command line. (Once upon a time you did have to do all that, believe it or not. Thank goodness those days are gone.)
Fortunately, Java has a number of different types of Listener suited for different tasks that take care of the complexity for you, and let your program do what you want it to do without you having to spell out every little detail. There are listeners for buttons, sliders and other controls such as trees, lists, focus changes, and so on. You can also write your own Listeners, so that you can create a new type of control and only ever have to deal with the inner complexities of how it works once.
What is a Listener?
A Listener is a connection between your program and something that creates an Event. An Event is a communication from a device on the computer or a program to something outside itself on the computer, like another program or device (through a program associated with that device, like its device driver.) In the case of our mouse program, the Listener is the connection between the mouse's button and our program. Whenever the left button is clicked, an Event is generated that contains what happened (a left-click) and the location in our window where it happened.
If the click happens outside our program's window, an Event is generated, but our program isn't included in the recipients of the message. If our program doesn't have a Listener, the mouse click Event gets passed to our program but is ignored.
If we have a Listener appropriate to an Event that's passed to our program, then something happens with it. So we have to create a Listener, tell our program to add it to its list of Listeners (which also tells the program what kind of events it's listening for.) Then our program will tell that Listener whenever one of those events happens, and pass along the details.
A MouseListener is a very generalized sort of Listener. An ActionListener, however, can be set up to listen for a specific event, like a click on a specific button. Take a look in the Java API at ActionListener. By associating an ActionListener with a specific button, you can hear only about when that button is clicked, and know that that's precisely what happened. That ActionListener won't hear about clicks elsewhere, you don't need to check the location of the click, and it won't tell you about anything else you don't want to hear about.
That saves you all the trouble that I talked about above. You can set up your ActionListener to just exeecute the part of your code you want it to run when someone clicks the button. Or slides the slider, or whatever. No fuss, no muss.
I'll be posting a sample program soon, until then have a look at the Sun Java Tutorials on using buttons and other controls from Swing (Java's best set of graphical user interface objects.)
By implementing the MouseListener interface, we were able to talk to the mouse very easily. However, a MouseListener is just one of the many types of Listener available in Java.
What Sort of Listener Are You?
If we tried to implement a full graphical interface in a program by using MouseListener, we'd have a lot of work to do. We'd have to draw all the buttons using drawing instructions in our program, then wait for mouse clicks. Once we got a click on something we'd have to figure out what had been clicked on by the location of the click in our window. Then we'd have to redraw the button (or slider, or whatever) to show that it had been clicked. Then we'd have to continue responding to the mouse by figuring out what the user is doing (clicking and releasing, clicking and dragging, or what) and make our program and the picture on the screen respond appropriately.
Whew! What a lot of work that would be! If we had to do that it'd almost be enough to drive you back to the command line. (Once upon a time you did have to do all that, believe it or not. Thank goodness those days are gone.)
Fortunately, Java has a number of different types of Listener suited for different tasks that take care of the complexity for you, and let your program do what you want it to do without you having to spell out every little detail. There are listeners for buttons, sliders and other controls such as trees, lists, focus changes, and so on. You can also write your own Listeners, so that you can create a new type of control and only ever have to deal with the inner complexities of how it works once.
What is a Listener?
A Listener is a connection between your program and something that creates an Event. An Event is a communication from a device on the computer or a program to something outside itself on the computer, like another program or device (through a program associated with that device, like its device driver.) In the case of our mouse program, the Listener is the connection between the mouse's button and our program. Whenever the left button is clicked, an Event is generated that contains what happened (a left-click) and the location in our window where it happened.
If the click happens outside our program's window, an Event is generated, but our program isn't included in the recipients of the message. If our program doesn't have a Listener, the mouse click Event gets passed to our program but is ignored.
If we have a Listener appropriate to an Event that's passed to our program, then something happens with it. So we have to create a Listener, tell our program to add it to its list of Listeners (which also tells the program what kind of events it's listening for.) Then our program will tell that Listener whenever one of those events happens, and pass along the details.
A MouseListener is a very generalized sort of Listener. An ActionListener, however, can be set up to listen for a specific event, like a click on a specific button. Take a look in the Java API at ActionListener. By associating an ActionListener with a specific button, you can hear only about when that button is clicked, and know that that's precisely what happened. That ActionListener won't hear about clicks elsewhere, you don't need to check the location of the click, and it won't tell you about anything else you don't want to hear about.
That saves you all the trouble that I talked about above. You can set up your ActionListener to just exeecute the part of your code you want it to run when someone clicks the button. Or slides the slider, or whatever. No fuss, no muss.
I'll be posting a sample program soon, until then have a look at the Sun Java Tutorials on using buttons and other controls from Swing (Java's best set of graphical user interface objects.)

Friday, September 5, 2008
Java's Documentation: A Closer Look
I started discussing the place to look up Java's classes and methods in Java's Reference Manual and the place to look up the language's syntax and elements in The Java Language Manual. Here I'm going to take a deeper look at the documentation of Java's classes, interfaces, and so on in the the Java API Reference.
At first glance the page that's presented to you by the API reference can be overwhelming. Too much information!
First let's look at what's in each panel. If you don't have the API reference open in another tab or window of your browser, open it now. I'll be referring to what you see. The link is the Java API Reference. Bookmark it. Put it on your bookmark bar. Don't tattoo it on your forearm, though--there'll be a new URL when a new version of Java hits the streets and you'd be really embarassed to walk around with an old URL tattooed on your arm, wouldn't you? Writing it on a sticky and putting it on your monitor's bezel is probably good enough.
In the upper left frame, we have the list of packages. So far so good. If you know what package has what you're looking for in it, you can reduce the stuff listed elsewhere a lot by clicking on the name of the package. For example, JFrame is in javax.swing. If you click on javax.swing in the upper left frame, you'll see a change in the display. Now only the classes, interfaces, and enums and exceptions defined in javax.swing are listed in the lower left frame. It's a much smaller list to scroll through. If you don't know the package you're looking for, then you'll just have to go through the long list, which is in alphabetical order.
In the upper left frame, click on "All Classes" at the top of the list to list all the classes, interfaces, enums, and exceptions in the API again.
Once you find your class on the lower left, you'll get its documentation in the main panel on the right. This can be overwhelming as well. Since we've already talked about JFrame, let's look at it. Click on JFrame in the lower left panel. You can select javax.swing in the upper left panel first to make selecting JFrame easier if you wish.
In the main window, you'll see the big title "Class JFrame". Immediately above that in small type is the package it is in. If you didn't already know that JFrame is in javax.swing, now you would know. Remember the package for when you think you're going to look something up again later. Or, if you want to include a class and don't know what package to
Beneath Class JFrame you'll see a list of other classes with little stairsteps leading down from one to another. These are the parent classes of JFrame, from the most basic object class in Java,
You can see the documentation for any of them by simply clicking on the class's name. But don't just yet, we're going to look at more of JFrame's documentation first.
Next down the page is the list of interfaces that JFrame implements. This means that JFrame has the methods implemented in it that these interfaces call for. There's a lot more to an interface than this, but that's a subject for another time. In essence, JFrame inherits the functions of these interfaces by implementing the methods they define.
Below the line, we have a text description of JFrame headed by a pseudocode definition of JFrame. Some of these text descriptions in Java's API Specification are very useful, others are less useful. The one for JFrame is middle of the road. Like many descriptions, it comes in at the middle of the story, assuming that you have complete and perfect familiarity with some other part of Java that isn't what you're looking up here. This results in some look-ups turning into searches for the start of the story. You look up JFrame, it refers to Frame, then you go back to Window to understand what they're talking about in java.awt.Frame's documentation. Then you're reading all about java.awt.Component, and so on. Before you know it, you're looking at java.lang.Object and wondering what your original question was, and where all the time has gone.
So don't rely to heavily on these. Scan them, but if you're not getting what you want, keep moving down. Usually the later parts of the section are far more informative and direct. If there's some meta-information you're looking for on a class, check the related tutorial at Sun, or do a web search and look for a good intro or tutorial article. (You might even scroll down below my articles to where I keep a long index to my articles.)
I'm going to skip on down past the Nested Class Summary and list of nested classes inherited, too, and jump right into the Field Summary below them.
Fields are the variables and constants defined for the class. The first listed have been defined directly in this class. The listing tells you what they've been defined as, and their purpose. Following that is a list of ones inherited from each of the parent classes.
The Constructor Summary tells you what constructors are available for this class. If you were hoping for a JFrame constructor that lets you set it visible and give it a size right at the outset, you'll see you're out of luck. JFrame's constructors only allow you to define either or both of the JFrame's title and graphics configuration when it's instantiated (that is, when the Constructor makes a new one.) So you'll have to set the size and visibility later.
How you set size and visibility, and do a bunch of other things with a JFrame comes next. They're part of the Method Summary. First there's the list of methods defined in JFrame. These are the new methods that JFrame adds to its parents' methods. Each lists its type and name and parameter list along with a brief description. Following comes the long, long list of inherited methods. JFrames have all these methods, too, but their description lies in the document page for the class they were originally defined in. Click on their name to go there.
Following this come the detailed descriptions of JFrame's fields and methods. You could have gotten here the fast way by clicking on one of the field or method names in the summaries above. These are the real meat of the Java API specification. They tell you how to use the class methods, and what they do. Once you know them, the short description in the summary will usually be enough for you (if you need even that.)
Having the whole document hyperlinked makes it far more useful than a paper document would be. There'd just be too much page-flipping.
If you want to have a copy right on your own machine, you can download the entire thing. The PDF is available from Sun for Java 6, or you can get it for different versions from links on the Java SE reference page.
That way you don't have to be on the network all the time, or held hostage to the speed of your connection to look up something.
At first glance the page that's presented to you by the API reference can be overwhelming. Too much information!
First let's look at what's in each panel. If you don't have the API reference open in another tab or window of your browser, open it now. I'll be referring to what you see. The link is the Java API Reference. Bookmark it. Put it on your bookmark bar. Don't tattoo it on your forearm, though--there'll be a new URL when a new version of Java hits the streets and you'd be really embarassed to walk around with an old URL tattooed on your arm, wouldn't you? Writing it on a sticky and putting it on your monitor's bezel is probably good enough.
In the upper left frame, we have the list of packages. So far so good. If you know what package has what you're looking for in it, you can reduce the stuff listed elsewhere a lot by clicking on the name of the package. For example, JFrame is in javax.swing. If you click on javax.swing in the upper left frame, you'll see a change in the display. Now only the classes, interfaces, and enums and exceptions defined in javax.swing are listed in the lower left frame. It's a much smaller list to scroll through. If you don't know the package you're looking for, then you'll just have to go through the long list, which is in alphabetical order.
In the upper left frame, click on "All Classes" at the top of the list to list all the classes, interfaces, enums, and exceptions in the API again.
Once you find your class on the lower left, you'll get its documentation in the main panel on the right. This can be overwhelming as well. Since we've already talked about JFrame, let's look at it. Click on JFrame in the lower left panel. You can select javax.swing in the upper left panel first to make selecting JFrame easier if you wish.
In the main window, you'll see the big title "Class JFrame". Immediately above that in small type is the package it is in. If you didn't already know that JFrame is in javax.swing, now you would know. Remember the package for when you think you're going to look something up again later. Or, if you want to include a class and don't know what package to
import
, this is a good way to find out.Beneath Class JFrame you'll see a list of other classes with little stairsteps leading down from one to another. These are the parent classes of JFrame, from the most basic object class in Java,
java.lang.Object
to JFrame itself. JFrame inherits from all these classes. Every method and field that they have, JFrame has, too.You can see the documentation for any of them by simply clicking on the class's name. But don't just yet, we're going to look at more of JFrame's documentation first.
Next down the page is the list of interfaces that JFrame implements. This means that JFrame has the methods implemented in it that these interfaces call for. There's a lot more to an interface than this, but that's a subject for another time. In essence, JFrame inherits the functions of these interfaces by implementing the methods they define.
Below the line, we have a text description of JFrame headed by a pseudocode definition of JFrame. Some of these text descriptions in Java's API Specification are very useful, others are less useful. The one for JFrame is middle of the road. Like many descriptions, it comes in at the middle of the story, assuming that you have complete and perfect familiarity with some other part of Java that isn't what you're looking up here. This results in some look-ups turning into searches for the start of the story. You look up JFrame, it refers to Frame, then you go back to Window to understand what they're talking about in java.awt.Frame's documentation. Then you're reading all about java.awt.Component, and so on. Before you know it, you're looking at java.lang.Object and wondering what your original question was, and where all the time has gone.
So don't rely to heavily on these. Scan them, but if you're not getting what you want, keep moving down. Usually the later parts of the section are far more informative and direct. If there's some meta-information you're looking for on a class, check the related tutorial at Sun, or do a web search and look for a good intro or tutorial article. (You might even scroll down below my articles to where I keep a long index to my articles.)
I'm going to skip on down past the Nested Class Summary and list of nested classes inherited, too, and jump right into the Field Summary below them.
Fields are the variables and constants defined for the class. The first listed have been defined directly in this class. The listing tells you what they've been defined as, and their purpose. Following that is a list of ones inherited from each of the parent classes.
The Constructor Summary tells you what constructors are available for this class. If you were hoping for a JFrame constructor that lets you set it visible and give it a size right at the outset, you'll see you're out of luck. JFrame's constructors only allow you to define either or both of the JFrame's title and graphics configuration when it's instantiated (that is, when the Constructor makes a new one.) So you'll have to set the size and visibility later.
How you set size and visibility, and do a bunch of other things with a JFrame comes next. They're part of the Method Summary. First there's the list of methods defined in JFrame. These are the new methods that JFrame adds to its parents' methods. Each lists its type and name and parameter list along with a brief description. Following comes the long, long list of inherited methods. JFrames have all these methods, too, but their description lies in the document page for the class they were originally defined in. Click on their name to go there.
Following this come the detailed descriptions of JFrame's fields and methods. You could have gotten here the fast way by clicking on one of the field or method names in the summaries above. These are the real meat of the Java API specification. They tell you how to use the class methods, and what they do. Once you know them, the short description in the summary will usually be enough for you (if you need even that.)
Having the whole document hyperlinked makes it far more useful than a paper document would be. There'd just be too much page-flipping.
If you want to have a copy right on your own machine, you can download the entire thing. The PDF is available from Sun for Java 6, or you can get it for different versions from links on the Java SE reference page.
That way you don't have to be on the network all the time, or held hostage to the speed of your connection to look up something.
Labels:
API,
documentation,
inheritance

Friday, July 11, 2008
The Java Virtual Machine: Adapter Cables for Your Computer's Insides
One of the problems programmers have is that different computer systems all require different ways to program them. Each computer has its own way of doing graphics and sound, its own way to talk to the keyboard and mouse, and so on. So a program written for one system wouldn't run on another.
We used to have this problem with the hardware on computers, too. If you had a Windows computer and an Apple display, they wouldn't hook up to each other. Apple computers and PCs used different video connectors. The keyboards and mice also had different connectors. The same was true of Unix workstations. They had their own connectors for their monitors, keyboards, and so on, and the connectors for Sun workstations were different from those for HP workstations.
While the outsides of computers are pretty standard now--you can hook up a PC monitor to a Mac and vice versa, the same for USB keyboards and mice--the insides are still just as weird as the outsides used to be. Each computer maker has their own connection for programs that want to talk to graphics, sound, keyboard and mouse, and so on.
Back in the old days we could hook up hardware from different manufacturers sometimes using adapter cables. In other cases, we had adapters that not only connected from one connector to another, but also translated the electronic signals.
For programmers that want to write programs that run on lots of different computer systems, the Java Virtual Machine (JVM) is like a bundle of adapter cables between your program and the computer system it's running on. No matter what system you are on, the JVM makes it look the same to your program:

This is why it's called a "virtual" machine. Java provides a sort of make-believe computer that we can program for. Then the JVM makes other computer systems pretend to be that make-believe computer. So programs written for that make-believe computer will run on any computer that has the JVM on it.
In this way the JVM acts like a whole bunch of adapter cables. On a Windows system it takes the oddball connector from its graphics system and adapts it to your program so that you can use familiar graphics objects and their methods. Similarly, it adapts the sound from OS X to your program, so that you can play music or sound effects. It adapts the filesystem from Unix so that you can read and write files using the same objects and methods as you would use on Windows or OS X. And so on. The JVM adapts all the major parts of a computer to your program, so that you can wrote one program and have it run on all major computer systems, rather than having to spend your time writing it over and over for different systems.
The system isn't perfect. The biggest problem has to do with how programs are "packaged" on each of the different systems. Your program will be the same, but the way you get it to act like a native program on each system for the user varies. The program itself will be the same, but it may need a "helper" file or some other item on each host system to make it look just like a program written directly for that system.
This will typically not be a concern for you as a programmer when you're starting out. And packaging your programs for each operating systems is a lot less work than learning all the ins and outs of how to program each system (or even just one of the systems.)
The JVM is such a useful tool that languages other than Java are being written to take advantage of it. Jython, for example, is a version of the python language that's written to use the JVM. It lets you write python programs that will run on any system with a JVM on it. Groovy is another such language. There's a long list of languages that run on the JVM in addition to Java.
We used to have this problem with the hardware on computers, too. If you had a Windows computer and an Apple display, they wouldn't hook up to each other. Apple computers and PCs used different video connectors. The keyboards and mice also had different connectors. The same was true of Unix workstations. They had their own connectors for their monitors, keyboards, and so on, and the connectors for Sun workstations were different from those for HP workstations.
While the outsides of computers are pretty standard now--you can hook up a PC monitor to a Mac and vice versa, the same for USB keyboards and mice--the insides are still just as weird as the outsides used to be. Each computer maker has their own connection for programs that want to talk to graphics, sound, keyboard and mouse, and so on.
Back in the old days we could hook up hardware from different manufacturers sometimes using adapter cables. In other cases, we had adapters that not only connected from one connector to another, but also translated the electronic signals.
For programmers that want to write programs that run on lots of different computer systems, the Java Virtual Machine (JVM) is like a bundle of adapter cables between your program and the computer system it's running on. No matter what system you are on, the JVM makes it look the same to your program:

This is why it's called a "virtual" machine. Java provides a sort of make-believe computer that we can program for. Then the JVM makes other computer systems pretend to be that make-believe computer. So programs written for that make-believe computer will run on any computer that has the JVM on it.
In this way the JVM acts like a whole bunch of adapter cables. On a Windows system it takes the oddball connector from its graphics system and adapts it to your program so that you can use familiar graphics objects and their methods. Similarly, it adapts the sound from OS X to your program, so that you can play music or sound effects. It adapts the filesystem from Unix so that you can read and write files using the same objects and methods as you would use on Windows or OS X. And so on. The JVM adapts all the major parts of a computer to your program, so that you can wrote one program and have it run on all major computer systems, rather than having to spend your time writing it over and over for different systems.
The system isn't perfect. The biggest problem has to do with how programs are "packaged" on each of the different systems. Your program will be the same, but the way you get it to act like a native program on each system for the user varies. The program itself will be the same, but it may need a "helper" file or some other item on each host system to make it look just like a program written directly for that system.
This will typically not be a concern for you as a programmer when you're starting out. And packaging your programs for each operating systems is a lot less work than learning all the ins and outs of how to program each system (or even just one of the systems.)
The JVM is such a useful tool that languages other than Java are being written to take advantage of it. Jython, for example, is a version of the python language that's written to use the JVM. It lets you write python programs that will run on any system with a JVM on it. Groovy is another such language. There's a long list of languages that run on the JVM in addition to Java.

Wednesday, July 2, 2008
A Most Basic Graphics App
Here's a simple graphics application in Java. It's about as simple as you can get while doing graphics.
Key points to note:
The line that reads g.drawLine(10,10,150,150); // Draw a line from (10,10) to (150,150) is the line that does the actual drawing. If you want to draw something else, or draw more things, replace this line with your own statements or add additional statements after this line. To see what you can do, check out the Graphics class in the Java API reference.
All of the items in blue,BasicPanel, need to match. You can just as well make it Foodle, but all of these need to match since this is the name of your class (and program.) Note that if you change it to Foodle, you need to save it in a file called Foodle.java, just as the file above needs to be saved in a file named BasicPanel.java
If you want to change the size of the window, change the 200,200 in the line reading frame.setSize(200,200); to some other number. Smaller numbers will make a smaller window, bigger numbers make a bigger window. The first number is how many pixels across it will be, the second number is how many pixels high it is.
Enjoy!
Technorati Profile
// Import the basic graphics classes.
import java.awt.*;
import javax.swing.*;
public class BasicPanel extends JPanel{
// Create a constructor method
public BasicPanel(){
super();
}
public void paintComponent(Graphics g){
g.drawLine(10,10,150,150); // Draw a line from (10,10) to (150,150)
}
public static void main(String arg[]){
JFrame frame = new JFrame("BasicPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
BasicPanel panel = new BasicPanel();
frame.setContentPane(panel);
frame.setVisible(true);
}
}
Key points to note:
The line that reads g.drawLine(10,10,150,150); // Draw a line from (10,10) to (150,150) is the line that does the actual drawing. If you want to draw something else, or draw more things, replace this line with your own statements or add additional statements after this line. To see what you can do, check out the Graphics class in the Java API reference.
All of the items in blue,BasicPanel, need to match. You can just as well make it Foodle, but all of these need to match since this is the name of your class (and program.) Note that if you change it to Foodle, you need to save it in a file called Foodle.java, just as the file above needs to be saved in a file named BasicPanel.java
If you want to change the size of the window, change the 200,200 in the line reading frame.setSize(200,200); to some other number. Smaller numbers will make a smaller window, bigger numbers make a bigger window. The first number is how many pixels across it will be, the second number is how many pixels high it is.
Enjoy!
Technorati Profile
Labels:
API,
application,
graphics

Friday, June 27, 2008
import Statements
An import statement is a way of making more of the functionality of Java available to your program. Java can do a lot of things, and not every program needs to do everything. So, to cut things down to size, so to speak, Java has its classes divided into "packages." Your own classes are part of packages, too.
No import Needed
The simple Hello.java program we've used as an example so far doesn't have any import statements:
Everything in the program is already available to the compiler. The compiler can access any class in the java.lang package without needing an import statement. It can also access any classes in the "local" package, which is any classes defined in files in the same directory as the program being compiled that aren't part of another package (that is, they don't have a package statement at the start of the file.)
import Required
Anything that isn't in the java.lang package or the local package needs to be imported. An example is the Scanner class. If you look up the Scanner class in the Java API Specification, you'll see that it is in the java.util package. Remember, to look it up you scroll to the class name in the lower left frame then click on it to bring up its definition in the main frame of the browser. Class names are in regular typeface, interfaces are in italics (some classes and interfaces have the same name.)
Here's an example program that uses Scanner, with an import statement:
We imported just the class Scanner from java.util in the import statement in this program. If we'd been using multiple classes from java.util, we could have made all the classes in java.util available to us by using this import statement:
import java.util.*;
The * is a "regular expression operator" that will match any combination of characters. Therefore, this import statement will import everything in java.util. If you have tried entering and running the example program above, you can change the import statement to this one.
If we need multiple classes from different packages, we use an import statement for each package from which we need to import classes (or interfaces, or any other part of that package we need.) It's not unusual to see a series of import statements near the start of a program file:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
Now, you may wonder why we have statements importing java.awt.* and java.awt.event.*. It seems like if you import java.awt.* that ought to import everything "under" java.awt, right? And the "dot" notation sure makes it look like java.awt.event is under java.awt.
Package Names and Those Misleading Dots
The thing is, each package with its own name is an entirely separate entity. The dot notation and name similarities are just a convention for making it easier to keep track of which packages have functions that are related to each other. One package isn't inside another one. java.awt.event is an entirely separate package from java.awt, it's not inside java.awt.
This can be very confusing, since the other use of the "dot notation" is a way of getting to something that is "inside" or a member of something else. System.out.println() is a way of getting at the println() method that's a member of out which is a member of the System class. But it doesn't work that way with packages. Each package name is a whole different package, and each package needs its own import statement. java.awt.event is entirely different from java.awt.
You can see package names in the API reference in the upper left frame. If you click on a package name, the lower left frame with change to limit what it shows to just the items in the package you've clicked.
No import Needed
The simple Hello.java program we've used as an example so far doesn't have any import statements:
public class Hello{
public static void main(String arg[]){
System.out.println("Hello.");
}
}
Everything in the program is already available to the compiler. The compiler can access any class in the java.lang package without needing an import statement. It can also access any classes in the "local" package, which is any classes defined in files in the same directory as the program being compiled that aren't part of another package (that is, they don't have a package statement at the start of the file.)
import Required
Anything that isn't in the java.lang package or the local package needs to be imported. An example is the Scanner class. If you look up the Scanner class in the Java API Specification, you'll see that it is in the java.util package. Remember, to look it up you scroll to the class name in the lower left frame then click on it to bring up its definition in the main frame of the browser. Class names are in regular typeface, interfaces are in italics (some classes and interfaces have the same name.)
Here's an example program that uses Scanner, with an import statement:
import java.util.Scanner;
public class ScannerTest{
public static void main(String arg[]){
// scanner gets its input from the console.
Scanner scanner = new Scanner(System.in);
String name = "";
// Get the user's name.
System.out.print("Your name, adventurer? >");
name = scanner.next();
System.out.println();
// Print their name in a a message.
System.out.println("Welcome, " + name + " to Javaland!");
}
}
We imported just the class Scanner from java.util in the import statement in this program. If we'd been using multiple classes from java.util, we could have made all the classes in java.util available to us by using this import statement:
import java.util.*;
The * is a "regular expression operator" that will match any combination of characters. Therefore, this import statement will import everything in java.util. If you have tried entering and running the example program above, you can change the import statement to this one.
If we need multiple classes from different packages, we use an import statement for each package from which we need to import classes (or interfaces, or any other part of that package we need.) It's not unusual to see a series of import statements near the start of a program file:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
Now, you may wonder why we have statements importing java.awt.* and java.awt.event.*. It seems like if you import java.awt.* that ought to import everything "under" java.awt, right? And the "dot" notation sure makes it look like java.awt.event is under java.awt.
Package Names and Those Misleading Dots
The thing is, each package with its own name is an entirely separate entity. The dot notation and name similarities are just a convention for making it easier to keep track of which packages have functions that are related to each other. One package isn't inside another one. java.awt.event is an entirely separate package from java.awt, it's not inside java.awt.
This can be very confusing, since the other use of the "dot notation" is a way of getting to something that is "inside" or a member of something else. System.out.println() is a way of getting at the println() method that's a member of out which is a member of the System class. But it doesn't work that way with packages. Each package name is a whole different package, and each package needs its own import statement. java.awt.event is entirely different from java.awt.
You can see package names in the API reference in the upper left frame. If you click on a package name, the lower left frame with change to limit what it shows to just the items in the package you've clicked.

Monday, June 23, 2008
The Java Language Manual
The Java language itself, as opposed to the classes, interfaces, and so on, is defined in the Java language specification, which can be found online. You can either view the online HTML version, or download a copy to your own system in several formats from this location:
http://java.sun.com/docs/books/jls/
This describes how Java programs are put together. It's not an easy read, it's written for compiler implementors more than it's written for programmers.
Look for "API, Language, and Virtual Machine Documentation", the link to view or download this document is in that section, titled "The Java Language Specification."
There are a few items of clarity in the document, like the section on Blocks (code blocks.)
For most programmers, especially beginners, the time to refer to this document is when you have a specific question in mind about some code you're writing that doesn't seem to want to compile. If you take a look at it occasionally, however, looking up things that you do understand and feel like you've got a handle on, it'll start making sense. Then you'll be able to make more use of it as your Java programming ability grows.
http://java.sun.com/docs/books/jls/
This describes how Java programs are put together. It's not an easy read, it's written for compiler implementors more than it's written for programmers.
Look for "API, Language, and Virtual Machine Documentation", the link to view or download this document is in that section, titled "The Java Language Specification."
There are a few items of clarity in the document, like the section on Blocks (code blocks.)
For most programmers, especially beginners, the time to refer to this document is when you have a specific question in mind about some code you're writing that doesn't seem to want to compile. If you take a look at it occasionally, however, looking up things that you do understand and feel like you've got a handle on, it'll start making sense. Then you'll be able to make more use of it as your Java programming ability grows.
Labels:
API,
code blocks,
documentation,
Java,
reference

Saturday, June 21, 2008
Java's Reference Manual
Java has a peculiar name for the reference where you look up Java classes and their methods and member variables. It's called the "API Specification." If you want to know what something does, or how to use it, you look it up in the Java API Specification for the version of Java that you're using.
The online home of these Java language reference manuals is at http://download.oracle.com/javase/
Look for the link here to "API Specification."
Here are direct links for several versions of Java in current use:
Java SE 5.0 (a.k.a. Java 1.5.0): http://download.oracle.com/javase/1.5.0/docs/api/
Java SE 6: http://download.oracle.com/javase/6/docs/api/
Java SE 7: http://download.oracle.com/javase/7/docs/api/
Your Java Version
To find the version of Java that you're using, open a Terminal or Command Line window and enter the command "java -version" (without the quotes, of course.) It will print out something like this:
java version "1.5.0_13"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_13-b05-241)
Java HotSpot(TM) Client VM (build 1.5.0_13-121, mixed mode, sharing)
The key item here is the information in the quotes in the first line, "1.5.0_13". For the purposes of figuring out which version of the API specification we want to be referring to, we look at the digits before the underscore. In this case, "1.5.0" is the part that's important to us. For this version of Java, we'd select the link for J2SE 1.5.0.
Another approach that's simpler is to simply go to the most recent API reference. Within the API reference, it lists what version of Java each feature appeared. You want to check that on each item before you dig into reading about what cool things it can do--it's terrible to spend a bunch of time reading about a class and methods that solve your programming problem only to have your compiler reject it because you're using a version that doesn't have that feature yet!
You also want to make sure that your compiler version matches your JVM version. "java -version" gives you the version of your JVM (Java Virtual Machine) a.k.a. Java Runtime Environment (they're not exactly the same thing, but close enough for this discussion and the terms JVM and JRE tend to get used interchangeably.)
To get your compiler version, enter the command "javac -version" at the Command Line or command prompt of your Terminal window. Some versions may want you to enter "javac --version" instead of "javac -version", so if you get a big long error message instead of a version message, try using two dashes (or read the usage message and see what it says, it may want "javac -v" or something.)
If your compiler version is newer than your JVM version, you'll want to follow the instructions for your system to point it to the newer JVM as a default so that you are interpreting your programs with the same version of Java that you are compiling it with. Your Java compiler may be compiling code that your JVM can't run, otherwise! The Java Development Kit (JDK), which contains the compiler, also has a JRE bundled with it that matches the version of the compiler. So you shouldn't have to download any updates to get a JRE that matches your compiler, you just have to let your system know which version of the JRE you want it to run.
How this is done varies between different operating systems, so consult the online information on how to do this for your OS or distro.
If your JRE is a newer version than your compiler, you'll probably want to update your compiler so that you can take advantage of all the features of your JVM. Once again, this is a system-specific process.
Looking Things Up in the Java API Specification
Once you're at the correct API specification (say language reference manual or library reference in your mind) you can find a list of classes on the lower left hand side (in the frames view.) Chances are you don't know what package the classes are in that you want to look up, at least at first, so scanning through the long alphabetic list of class names is usually the place to start. There are also names in italic, these are names of interfaces.
Let's say we want to look up System.out.println() which has appeared in many of our examples here. The class name is System, so we click on System in the lower left hand frame. This makes the documentation page for System appear on the right side frame.
Above the words "Class System" you'll see the name of the package that System is part of, java.lang. Click on java.lang in the upper left hand frame and you'll see that it updates the lower left frame to show a much shorter list, a list of the interfaces, classes, enums, and errors that are part of the java.lang package. It's worthwhile to remember the package your commonly used classes are part of, for this and other reasons.
We wanted to look up System.out.println(). Back on the main frame on the right side of the window we can scroll down a little to see the Field Summary, where out is listed. This field, or member variable, is System.out. Click on out.
out is a PrintStream object, which means that it has all the methods of the PrintStream class, among other things. Below its verbose description is a set of links to PrintStream methods, including PrintStream.println(). Click on this link now.
This takes you to a list of different versions of the println() method, which do different things depending on what sort of data is inside the parentheses. In the examples we've been using so far, we've been using "System.out.println("Hello")" so we've been putting String data inside the parens ("Hello").
If we scroll down a bit we see println(String x), which tells us what the expected behavior is for a call of println() with a string inside the parens.
Try looking up some other classes and methods. For example, take a look at what the Scanner class can do.
The online home of these Java language reference manuals is at http://download.oracle.com/javase/
Look for the link here to "API Specification."
Here are direct links for several versions of Java in current use:
Java SE 5.0 (a.k.a. Java 1.5.0): http://download.oracle.com/javase/1.5.0/docs/api/
Java SE 6: http://download.oracle.com/javase/6/docs/api/
Java SE 7: http://download.oracle.com/javase/7/docs/api/
Your Java Version
To find the version of Java that you're using, open a Terminal or Command Line window and enter the command "java -version" (without the quotes, of course.) It will print out something like this:
java version "1.5.0_13"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_13-b05-241)
Java HotSpot(TM) Client VM (build 1.5.0_13-121, mixed mode, sharing)
The key item here is the information in the quotes in the first line, "1.5.0_13". For the purposes of figuring out which version of the API specification we want to be referring to, we look at the digits before the underscore. In this case, "1.5.0" is the part that's important to us. For this version of Java, we'd select the link for J2SE 1.5.0.
Another approach that's simpler is to simply go to the most recent API reference. Within the API reference, it lists what version of Java each feature appeared. You want to check that on each item before you dig into reading about what cool things it can do--it's terrible to spend a bunch of time reading about a class and methods that solve your programming problem only to have your compiler reject it because you're using a version that doesn't have that feature yet!
You also want to make sure that your compiler version matches your JVM version. "java -version" gives you the version of your JVM (Java Virtual Machine) a.k.a. Java Runtime Environment (they're not exactly the same thing, but close enough for this discussion and the terms JVM and JRE tend to get used interchangeably.)
To get your compiler version, enter the command "javac -version" at the Command Line or command prompt of your Terminal window. Some versions may want you to enter "javac --version" instead of "javac -version", so if you get a big long error message instead of a version message, try using two dashes (or read the usage message and see what it says, it may want "javac -v" or something.)
If your compiler version is newer than your JVM version, you'll want to follow the instructions for your system to point it to the newer JVM as a default so that you are interpreting your programs with the same version of Java that you are compiling it with. Your Java compiler may be compiling code that your JVM can't run, otherwise! The Java Development Kit (JDK), which contains the compiler, also has a JRE bundled with it that matches the version of the compiler. So you shouldn't have to download any updates to get a JRE that matches your compiler, you just have to let your system know which version of the JRE you want it to run.
How this is done varies between different operating systems, so consult the online information on how to do this for your OS or distro.
If your JRE is a newer version than your compiler, you'll probably want to update your compiler so that you can take advantage of all the features of your JVM. Once again, this is a system-specific process.
Looking Things Up in the Java API Specification
Once you're at the correct API specification (say language reference manual or library reference in your mind) you can find a list of classes on the lower left hand side (in the frames view.) Chances are you don't know what package the classes are in that you want to look up, at least at first, so scanning through the long alphabetic list of class names is usually the place to start. There are also names in italic, these are names of interfaces.
Let's say we want to look up System.out.println() which has appeared in many of our examples here. The class name is System, so we click on System in the lower left hand frame. This makes the documentation page for System appear on the right side frame.
Above the words "Class System" you'll see the name of the package that System is part of, java.lang. Click on java.lang in the upper left hand frame and you'll see that it updates the lower left frame to show a much shorter list, a list of the interfaces, classes, enums, and errors that are part of the java.lang package. It's worthwhile to remember the package your commonly used classes are part of, for this and other reasons.
We wanted to look up System.out.println(). Back on the main frame on the right side of the window we can scroll down a little to see the Field Summary, where out is listed. This field, or member variable, is System.out. Click on out.
out is a PrintStream object, which means that it has all the methods of the PrintStream class, among other things. Below its verbose description is a set of links to PrintStream methods, including PrintStream.println(). Click on this link now.
This takes you to a list of different versions of the println() method, which do different things depending on what sort of data is inside the parentheses. In the examples we've been using so far, we've been using "System.out.println("Hello")" so we've been putting String data inside the parens ("Hello").
If we scroll down a bit we see println(String x), which tells us what the expected behavior is for a call of println() with a string inside the parens.
Try looking up some other classes and methods. For example, take a look at what the Scanner class can do.
Labels:
API,
documentation,
Java,
Java version,
JDK,
JVM,
packages,
reference,
System.out.println()

Subscribe to:
Posts (Atom)
Subjects:
- Android (3)
- angle brackets (1)
- API (15)
- applet (2)
- application (15)
- arguments (2)
- array (3)
- array initializer (1)
- assignment (3)
- asterisk (2)
- beginner (8)
- book review (4)
- C (1)
- C# (1)
- C++ (1)
- calculations (4)
- classes (8)
- code blocks (3)
- collection (6)
- collision detection (3)
- command line (7)
- Comments (1)
- comparison (3)
- constants (1)
- constructor (2)
- cross-platform (1)
- curly braces (3)
- dates (1)
- declaration (4)
- documentation (3)
- dot notation (1)
- embedded (1)
- environment (11)
- equals (2)
- events (3)
- example (2)
- expressions (2)
- file (3)
- file names (1)
- framework (3)
- generics (2)
- graphics (22)
- graphics Swing CSS (1)
- heavyweight component (1)
- humor (1)
- i/o (3)
- IDE (9)
- import (2)
- inheritance (2)
- initializer (1)
- inner class (5)
- input (5)
- interface (3)
- Java (27)
- Java version (7)
- Javascript (1)
- JDK (5)
- JFrame (6)
- JPanel (7)
- JVM (10)
- lightweight component (2)
- List (3)
- listeners (3)
- literal (1)
- local (1)
- loop (2)
- main() (4)
- Math (3)
- method (4)
- methods (2)
- modulo (1)
- mouse (1)
- name (2)
- numeric (2)
- object code (1)
- objects (3)
- operators (4)
- output (3)
- packages (5)
- paint() (3)
- paintComponent() (4)
- parentheses (1)
- percent sign (2)
- PHP (1)
- public (2)
- read (2)
- reference (8)
- regular expressions (1)
- Resources (5)
- restore (1)
- save (1)
- Scanner (1)
- semicolons (1)
- signature (4)
- source code (4)
- square brackets (1)
- star (1)
- static (2)
- Swift (1)
- System.out.println() (2)
- threads (2)
- trigonometry (1)
- type (8)
- variables (9)
- video game (8)
- virtual machine (2)
- void (2)
- web (2)
- why java (9)