The Java Tutorials' Weblog
Preparing for Java Programming Language Certification
When we updated the core Java Tutorial to JDK 6, we included a page designed to help those who are studying for Java Programming Language Certification. This study guide calls out which portions of the tutorial are relevant to the testing objectives -- it is by no means comprehensive. Nor does it discuss the test and what to expect.We still sometimes receive questions on the tutorial feedback alias asking how to prepare for the Java Programmer Certification test. The book strongly recommended by our Java instructors and course developers is the Complete Java 2 Certification Study Guide by Philip Heller.
You can follow this thread on the Java Tutorials Community forum.
-- Sharon Zakhour
Posted at 07:48AM May 20, 2008 by The Java Tutorial Team | Comments[4]
DefaultTreeModel -- Adding, Removing and Updating Nodes
Many moons ago I had a discussion with Collin Fagan (Java Tutorial contributor and all around helpful guy) about the fact that I had seen some requests for a tutorial on how to add, remove and update nodes in a DefaultTreeModel.Collin wasted no time creating such an example. Unfortunately, resources being what they are, I wasn't able to get engineering cycles for reviewing the example. Because we generally don't include material that hasn't been reviewed by engineering, it was backburnered.
Meanwhile, Collin posted his example and some accompanying text, The Secret Life of a DefaultTreeModel on JavaLobby.
Collin has now posted his example on the JavaTutorials forum!
When you compile and run the example (it will run under JDK 5) it brings up a panel containing a tree with a root node. When you open the root node you'll see three child nodes. At this point you can right-click any of the nodes (control-click on a Mac) and you can add 50 children to the current selection, remove the current selection, or modify the text on the current selection.
Thanks for this very useful example, Collin!
-- Sharon Zakhour
Posted at 02:46PM May 16, 2008 by The Java Tutorial Team | Comments[0]
JTable: Freezing a column while scrolling the others
Have you ever needed to create a table that is too wide for the view so it requires a horitzonal scrollbar? OK, that's pretty routine. But have you then wanted one (or more) of the columns to remain fixed when you scroll the other columns?Over on the javatutorials portal Collin Fagan has posted an example that shows how to do just that. Check out Row Labels/Frozen Columns. (You'll have to scroll down through several posts to see it.)
Thanks Collin!
-- Sharon Zakhour
Posted at 02:51PM May 13, 2008 by The Java Tutorial Team | Comments[2]
JTable Examples
Earlier this week I announced the Java Tutorials Community Portal. On the portal there is a forum where you can enjoy tutorial-related chat. To kick things off, I started a thread asking what you would like to see added to theJTable tutorial. I want to thank Collin Fagan (aka aberrant) who has been posting some JTable examples.
Please check it out!
-- Sharon Zakhour
Posted at 12:38PM May 07, 2008 by The Java Tutorial Team | Comments[0]
Announcing the Java Tutorials Community Portal
You are most likely aware of the java.net community the place for Java information and collaboration. The Java Tutorials now have a presence on java.net The Java Tutorials Community Portal.This is the place to talk about the tutorials how you use them, how you extend them (or would like to), new tutorials you would like to see or even contribute. You can share ideas, curriculum, code examples (either new or modified from existing examples).
To participate on the wiki and the forum you need to register on java.net (it's free). That's all you need to do.
Hope to see you there!
-- Sharon Zakhour
Posted at 08:18AM May 05, 2008 by The Java Tutorial Team | Comments[2]
SwingSet3
If you program your GUI using Swing, you are probably familiar with the SwingSet2 demo that is bundled with the JDK. SwingSet2 was created for release 1.3 of the JDK. Are you aware that SwingSet3, for use with release Java SE 6 update 10, is now available on java.net?
This new version, written by Swing expert, Amy Fowler, boasts a slick GUI showcasing the Nimbus look and feel. This demo is visually beautiful and extensible, but what I really love is the new feature that allows you to view the code used to create and display the selected component. One half of a split pane displays the selected component and the other half shows the code. For some complex components, such as JTable and JButton, a combo box allows you to choose exactly what snippet of code produces a particular effect.
You can obtain SwingSet3 from swingset3.dev.java.net.
(If, like me, are you a Mac OS X user, you need to be running the latest version of JDK 6 from Apple that runs only under Leopard.)
Check it out!
-- Sharon Zakhour
Posted at 02:51PM Apr 22, 2008 by The Java Tutorial Team | Comments[3]
Animation, the Easy Way!
If you've ever programmed animations and thought "there must be an easier way", then today's blog entry is sure to bring welcomed relief. The JavaFXTM Script programming language now supports key frame animation, which allows you to declare your animations using a simple syntax that resembles plain English. All graphics rendering now happens automatically, behind the scenes, allowing you to focus on the animation at hand rather than the "plumbing" to make it all work.
To demonstrate this functionality we will re-create the classic "tumbling
duke" animation. Since this may be your
first exposure to the language, we'll break this discussion up into
two separate entries: today we will cover the basics;
early next week we'll cover everything else.
You'll want to try this code for yourself, but fear not, the development
environment is easy to set up.
The edit-compile-run process is similar to that of
the JavaTM programming language,
but the commands are
javafxc and javafx instead of
javac and java.
There is also a JavaFX Script compiler plug-in available for the NetBeans IDE, for
those who prefer not to work from the command line.
For instructions on setting up any of these environments, visit the
openjfx project page
at http://openjfx.dev.java.net.
Having said that, let's get animating!
As you may already know, the tumbling duke animation is comprised of 17 separate images. Traditionally, creating this animation has required an intimate understanding of the AWT and Swing painting mechanisms (if you haven't seen it before, take a look at the original Tumbling Duke source code.) As you will soon learn, accomplishing the same end result using JavaFX Script technology is a simple matter once you've mastered its syntax.
import javafx.ui.*;
import javafx.ui.canvas.*;
import javafx.animation.*;
// Load image data
var images = for (i in [1..17]) {
Image { url: "file:images/T{i}.gif"};
}
...
|
Listing 1: Importing Classes and Loading Images
Our first task is to load the images into memory. If your initial instinct
is to place these images into an array, you're right, although here that data structure is known as a sequence. Sequences differ from Java programming language arrays, but are similar in that
they also hold a list of objects.
Sequences
are generally declared with square brackets (the code [1..17] is a sequence), but the system will also infer this based on context when needed.
Such is the case with our var images declaration.
The for loop that follows
returns one javafx.ui.Image object per iteration;
when it's done, you end up with an images variable
that contains all of the image data.
(If you're wondering where the constructor
call is, the JavaFX Script programming language uses object literals; the code
Image{} is enough to return a new Image object.)
...
// Create timeline and key animation frames
var t = Timeline {
keyFrames: for (image in images) {
KeyFrame {
time: 100ms* indexof image
action: function(){currDuke=image;}
}
}
}
...
|
Listing 2: Creating the Key Frames and Animation Timeline
Next, we'll create the animation's key frames and place them on a timeline. These constructs are
represented by the javafx.animation.KeyFrame and javafx.animation.Timeline classes,
respectively. In the interest of saving space we've rolled a lot of functionality into the above code,
so let's take a minute to make sure you understand what's going on.
In the JavaFX Script programming language, an object's state is
stored in its attributes.
Above we initialize the keyFrames attribute
of the Timeline class, followed by the time and action attributes of the KeyFrame class.
So far as the animation itself is concerned, the important concepts are that a "key frame" (a KeyFrame instance) represents one specific point in time along your animation,
and a Timeline instance holds a sequence of KeyFrame objects. It's up to you to decide where the key frames of your
animation should be; in this case we consider each flip of the image to be one frame in the animation. It seems reasonable that the images
should change 100 milliseconds apart, so we've initialized each key frame with a time value that is 100ms greater than the previous frame.
The action attribute of the KeyFrame class accepts a function; that function can contain any code that you want. Keep in mind that we're looping through each of the images where this occurs, so the only action that we care about is assigning the current image of the current key frame to a
separate
variable named currDuke. As you will see below, this currDuke variable is where the GUI will look to find the current image.
...
// Set first image to be displayed
var currDuke = images[0];
// Create the GUI application frame
Frame {
title: "Tumbling Duke"
width: 400
height: 150
background: Color.WHITE
visible: true
content: FlowPanel {
content: Canvas {
onMouseClicked: function(e) {t.start();}
content: ImageView {
image: bind currDuke;
}
}
}
}
|
Listing 3: Creating the Application GUI
At this point, all that's left to do is to construct the GUI. This is actually the easiest part; all we need to do
is create a few objects and we're done.
The image attribute of the ImageView class is the
actual image that will appear on screen. The code "image: bind currDuke" is the magic that keeps the GUI in sync with the
images used in our timeline. By "binding" the image attribute
to the currDuke variable, the
on-screen image will automatically change whenever the value of currDuke changes.
In this early version of the code, we'll tell the animation timeline to begin only when the user clicks somewhere on the GUI's drawing surface. In the next blog entry we'll change that behavior to an infinite loop that begins automatically, thereby replicating the behavior of the original animation.
import javafx.ui.*;
import javafx.ui.canvas.*;
import javafx.animation.*;
// Load image data
var images = for (i in [1..17]) {
Image { url: "file:images/T{i}.gif"};
}
// Create timeline and key animation frames
var t = Timeline {
keyFrames: for (image in images) {
KeyFrame {
time: 100ms* indexof image
action: function(){currDuke=image;}
}
}
}
// Set first image
var currDuke = images[0];
// Create the GUI application frame
Frame {
title: "Tumbling Duke"
width: 400
height: 150
background: Color.WHITE
visible: true
content: FlowPanel {
content: Canvas {
onMouseClicked: function(e) {t.start();}
content: ImageView {
image: bind currDuke;
}
}
}
}
|
Listing 4: The Complete Code Listing The listing above shows the complete source code so far. Be sure to check back next week for the continuation of this discussion!
-- Scott Hommel
Posted at 10:38AM Apr 09, 2008 by The Java Tutorial Team | Comments[6]
Searching the Java Tutorials
In the past we have received feedback that it is difficult to search the tutorials. In the banner of every page there is a link to a search page, but some people find the results of a search hard to wade through.Another easy way to find a subject in the tutorials is to use the Really Big Index. This index has always been available, but not everyone has been aware of it. For this most recent release of the tutorial, we have made it easier to find the Really Big Index. If you look at the tutorial's main page, you'll see that there is now a Tutorial Contents box on the upper right and a button in that box will lead you directly to the Really Big Index.
We hope you find this to be a useful feature for searching the contents of the tutorials.
- Sharon Zakhour
Posted at 04:39AM Apr 04, 2008 by The Java Tutorial Team | Comments[2]
Web Push of the Java Tutorials
We have just released another update of The Java Tutorials.The biggest change, content-wise, is the newly re-worked Drag and Drop and Data Transfer lesson.
The other big change is that we have moved the download of the tutorials to the Sun Download Center. You can download the tutorials in their entirety from that location.
As part of this process, we have updated the license used to distribute the tutorials. (You click-to-accept the license when you perform the download.) The updated license is now tailored to encourage academic and non-commercial use without any special permission from Sun.
Sharon Zakhour
Posted at 12:10PM Mar 19, 2008 by The Java Tutorial Team | Comments[1]
Superpackages
You may be aware of packages in Java (and if you're not, check out the tutorial page, What Is a Package?), but have you heard of superpackages? It is one of the features slated for JDK7.As you probably know, you can organize your code into a package. In the Swing tutorial, we put the examples into packages. The drag and drop examples are in the dnd package, the button, slider, and menu examples are in the components package, the SpringLayout and GridLayout examples are in the layout package, and so on. Even when you don't specify a package, your code goes into the default package.
But superpackages allow you to specify a much more sophisticated hierarchy to your code. You can nest superpackages: a superpackage may contain one or more packages and one or more superpackages. You can choose how much you want to expose of the nested superpackages.
For more information about this upcoming feature, see
- Strawman Proposal for JSR 294 Superpackages
- JSR 294 - Improved Modularity Support in the Java Programming Language
-- Sharon Zakhour
Posted at 02:48PM Jan 07, 2008 by The Java Tutorial Team | Comments[4]
Confusion about the Class Variable Q&E Page
Until very recently one of the questions on the Questions and Exercises: Classes page looked like this:1. Consider the following class:The answer for part (c) confused some of you:public class IdentifyMyParts { public static int x = 7; public int y = 3; } a. What are the class variables? b. What are the instance variables? c. What is the output from the following code: IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; IdentifyMyParts.x = 1; b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("IdentifyMyParts.x = " + a.x); System.out.println("b.x = " + b.x);
a.y = 5
b.y = 6
IdentifyMyParts.x = 2
b.x = 2
In fact we've received twenty emails in the last year from people who thought the tutorial was in error — that the correct value for a.x (and therefore the value of IdentifyMyParts.x) should be
1.
Actually the answer is correct, though it doesn't offer any explanation. The point of this question was to have you think about class variables. (In fact, the writer wrote IdentifyMyParts.x rather than a.x to give you a clue that this is a class variable.) What makes x a class variable is defining it as a public static int. This means that there is a single instance of x that is shared across every instance of IdentifyMyParts. When the first line of the following code snippet is executed:
IdentifyMyParts.x = 1;
b.x = 2;
Then x has a value of 1 for less than a nanosecond. When the second line of code is executed, x is set to a value of 2. Whether you call it IdentifyMyParts.x, a.x or b.x, it all refers to the same entity. For more information, see Understanding
Instance and Class Members.
As a result of your feedback, we have improved the question and the answer.
Your continued feedback helps us improve the tutorial. Thanks!
-- Sharon Zakhour
Posted at 08:16AM Dec 21, 2007 by The Java Tutorial Team | Comments[1]
Java Equivalent for sprintf
We received this question on the Tutorial Feedback alias:
I was reading your tutorial on format. You can do something likeSystem.out.format ("a = %05d\n", 32 )which should printa = 00032This is equivalent toprintf( "a = %5.5d\n", a );in C++. I want to simulatesprintfin Java, like:char b[20]; sprintf( b, "%5.5d", 22);thenbwould contain the string00022.That is, I want a way in Java to do an
Integer.toString()but be able to specify a width and have it insert leading 0's. Ifgcontained the integer value22, I would want something likeg.toString(5)to return00022instead of just"22"or" 22".Any way to do that?
Why, yes, there are a couple ways to accomplish this!
If you are writing an application that must be localized and internationalized, you may want to use DecimalFormat, like this:
DecimalFormat myFormatter = new DecimalFormat("00000");
String s2 = myFormatter.format(22);
You can refer to the Internationalization tutorial for more information.
DecimalFormat uses the rather arcane text APIs.
If you don't need something this heavy-duty, you may want to use the
java.util.Formatter
class, introduced in JDK 5. The String.format methods provide a front-end to the Formatter class. To accomplish the above task using String.format, the code would look like this:
String s1 = String.format("'%05d'%n", 22);
If you want the output to go somewhere other than a string - to a file or to System.out, for example - you would probably use the Formatter class directly.
For further information, check out these pages in the tutorial:
- Formatting Numeric Print Output
- Strings - see the section "Creating Format Strings"
If you are using an earlier release than JDK 5, you might be interested in this Formatted Printing for Java (sprintf) article.
As a result of this question, I've tweaked the tutorial a bit, so thanks for the feedback!
-- Sharon Zakhour
Posted at 12:48PM Dec 18, 2007 by The Java Tutorial Team | Comments[3]
Interested in Writing about Java SE?
Are you becoming familiar with Java? Do you enjoy the challenge of describing technical information in writing?We are looking for a recent college grad who wants to develop as a technical writer and who can work out of our Santa Clara campus.
For more information (and to submit your resume), see our job posting.
-- Sharon Zakhour
Posted at 11:24AM Nov 13, 2007 by The Java Tutorial Team | Comments[9]
The Inner Class Example Page
Our Core Tutorial has recently been updated as a result of your feedback. We modified the page that demonstrates the use of the inner class by simplifying it and thus focusing particularly on inner classes. Now, when we talk about inner classes, we no longer use complex data structures like stacks and complex algorithms related to them. Let's just take an array and step through it, picking even values. Simple and clear.For those of you who enjoyed the stack example, don't worry. In addition to the example we mentioned earlier, we updated the one about stacks as well. It uses a stack based on an array, and push and pop methods to implement the FILO method and an inner class. To show the inner class in action, we 'expand' the stack functionality by stepping through it and picking its even values (this is not allowed for 'standard' stacks, as you probably remember). In brief: we push, pick even, and then pop. See the following link to view the updated stack example.
In conclusion, we would like to ask your opinion about this tutorial change. What do you think? Let's make our tutorial the most effective and useful that it can be. After all, isn't that the most important thing about tutorials? :)
-- Dmitry Bondarenko
Posted at 09:25AM Nov 09, 2007 by The Java Tutorial Team | Comments[2]
Java Beans and the NetBeans IDE
We want to know your opinion on the sensitive issue affecting the Java Beans functionality in the NetBeans IDE.Many releases of NetBeans contained the Beans module - a robust visual tool to create a custom bean, add a property with the Bean Pattern, and edit bean info with the BeanInfo editor. Those features were covered in the Java Beans trail of the Java Tutorial, and some features were discussed in this blog.
Unfortunately, due to a variety of circumstances (see the NetBeans project page for more information) the Beans module was dropped from the 6.0 release of NetBeans. This may impede bean application development. Many typical bean operations are not available through the NetBeans 6.0 GUI, which makes creating a custom bean more than a five-minute task. Additionally, the newly introduced binding functionality will be cruelly limited in the IDE, because even to simply add a bound property you will have to code the getter and setter methods by hand.
So this blog offers you a chance to vote for bringing back the Beans module in the upcoming update release of NetBeans. Please leave your comments in support of the Java Beans functionality.
-- Alla Redko
Posted at 05:37AM Oct 29, 2007 by The Java Tutorial Team | Comments[47]
Tuesday May 20, 2008