Building a Simple Java Application in Mac OS X
Pages: 1, 2, 3
Let the user pick the color
Instead of hard-coding the color into the application, we could allow the user to select the background color when the application starts up. We'll do this by displaying a JColorChooser that allows the user to pick from a palette of colors. One nice resource for viewing your widget options for Swing components is the Visual Index to the Swing Components. It is part of the Java Tutorial. Just remember -- they all look better running on a Mac.
The JColorChooser allows the user to select a color and it returns a color that can be used as the argument to the setBackground() method that we used in our first iteration of EachSquare. Alter the EachSquare.java code as follows.
package NineSquares;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JColorChooser;
public class EachSquare extends JPanel {
public EachSquare() {
setBackground( JColorChooser.showDialog(
this, "Choose Background Color", getBackground()));
}
}
To run the JColorChooser from a dialog box, we call the JColorChooser.showDialog() method. It takes three arguments. The first is the component that we're setting the color for. The second is a useful message to the user. The third is the initial color of the component being colored in. It is up to you to make sure these items all match.
If you are getting and setting the background color and send a message to the user such as "Choose Font Color," you will baffle the user. Notice that you have isolated the changes from the other objects. Your NineSquares object and MainFrame object do not need to know how the color is being selected. Save your changes, compile and run the application, and the following screen will pop up before you see your floating window.

NineSquares
Now let's add more than one square to our frame. When you are arranging visual components within a container you are leaving the world of the Aqua interface guidelines. The Java way is for you to rely on Sun's Layout Managers. You can choose how you want the basic container to be laid out, and then add components to the container and let the Layout Manager decide where they go.
In our case, we will add nine squares in a three-by-three grid using the GridLayout. Instead of creating one EachSquare object, we will create nine of them and add them to the the MainFrame content pane. The MainFrame.java file needs to be modified like this.
package NineSquares;
import javax.swing.JFrame;
import java.awt.GridLayout;
public class MainFrame extends JFrame{
public MainFrame() {
super("Nine Squares");
getContentPane().setLayout(new GridLayout(3,3));
for (int i = 0; i<9; i++) {
getContentPane().add(new EachSquare());
}
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
We need to import the GridLayout class, and then we set the layout of the content pane to a new GridLayout that is three by three. Next, we create nine EachSquares and add them to the content pane. We're getting a lot with very few code changes. Now let's take a look at the changes to EachSquare.java.
package NineSquares;
import javax.swing.JPanel;
import java.awt.Color;
public class EachSquare extends JPanel {
public EachSquare() {
setBackground(new Color((int)(Math.random()* 16777215)) );
}
}
We've just created a color in a new way. Instead of specifying a constant color or using a JColorChooser, we're picking a random number between 0 and 2^24-1. You'll notice that we didn't have to import the Math class. This is because it is part of the java.lang package and is automatically available to you. When you run the application, you get a window that looks something like this.

Responding to mouse clicks
So far, our application isn't very responsive. In this next version, we'll still bring up nine squares where the colors are randomly selected, but this time we'll give the user the chance to alter them. If a user clicks on a square, a JColorChooser dialog will pop-up and allow them to change the background color. The only changes we will make are in the EachSquare.java file. It will now look like this.
package NineSquares;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JColorChooser;
public class EachSquare extends JPanel {
public EachSquare() {
setBackground(new Color((int)(Math.random()* 16777215)) );
addMouseListener(new MouseClickListener());
}
public class MouseClickListener extends MouseAdapter{
public void mouseClicked(MouseEvent e) {
setBackground(JColorChooser.showDialog(
EachSquare.this, "Choose Background Color", getBackground()));
}
}
}
The big change here is the MouseClickListener. This subclass of MouseAdapter waits around for a message that there's been a mouse click that it cares about. It then creates a JColorChooser with a beginning color matching the background color of this panel. When the user selects the new color and dismisses the dialog box, the background color for the panel is set to this new choice.
The MouseClickListener is actually defined from inside the EachSquare class and is called an "inner class." The line addMouseListener( new MouseClickListener()) is what associates the MouseClickListener with this particular panel. When a panel is clicked on, its MouseClickListener responds. The only other changes to the file are to add the appropriate imports.
Summary
Although this wasn't really an introduction to Java, I hope it helps you see how easy it is to create simple applications for Mac OS X using the language. You may find that you work better with an IDE that does most of this visual work for you. With most of them, you can drag these visual components onto a workspace and quickly customize the properties to get the look and action that you want. For an application of this scope, it wasn't that hard to implement it from scratch using simple tools.
As a challenge, take a look at this month's issue of Mac Tech. Its challenge is to get you to write a version of Dots. The puzzling thing, however, is that Mac Tech has specified the IDE you must use and a choice of languages. Java is not among your choices. For kicks, let's take a shot at Dots in Java. Feel free to use the discussion forums below to enlist the help of others.
Daniel H. Steinberg is the editor for the new series of Mac Developer titles for the Pragmatic Programmers. He writes feature articles for Apple's ADC web site and is a regular contributor to Mac Devcenter. He has presented at Apple's Worldwide Developer Conference, MacWorld, MacHack and other Mac developer conferences.
Read more Java Programming on the Mac columns.
Return to the Mac DevCenter.
You must be logged in to the O'Reilly Network to post a talkback.
Showing messages 1 through 26 of 26.
-
Great intro to Java
2006-03-01 11:08:07 ramkelath [Reply | View]
I saw this article a few years ago and meant to work through it. This week I'm in between projects and got to revisit it this morning. Installed the XCode package that comes with Tiger and I was off and running. I particularly like the way the author introduces key concepts like refactoring, package/folder management, documentation lookup and more in bite-sized steps. It took me a little time to figure out that I had to compile from outside the directory that the package was defined in. The number of tiny but important concepts to be mastered is still daunting, but my experience with this will hopefully help me consider tackling them.
-
Good Article
2005-05-31 23:58:38 P2 [Reply | View]
Thanks for a good, simple and clear article. I recently did a short course in Java, using Jgrasp on both PC and Mac, which really helped understanding what was happening in this article. It was fun to work in the Terminal instead of jGrasp, using javac and pico as text editor. I had a problem compiling at first because I tried compiling from inside the NineSquares folder, as others have done. As is pointed out in the author's responses you have to compile outside of the folder NineSquares for it to work.
A number of users have complained about things not compiling, or not understanding what the problem was. If one reads the javac compiler error messages its generally quite clear where one should look. It very often comes down to one's own obscure spelling mistakes: my best was "Adaptor" instead of "Adapter".
I haven't found the Java documentation referred to in the article yet either, but as it was written about 3 years ago that's not surprising. Things change. The Developer Tools Java docs are easy to find though, and in any case Java documentation is available online in various places.
-
cannot compiles NineSquares
2004-02-04 13:30:15 wchild [Reply | View]
I typed in the program (actuallly copied it), and got the following error message:
error: cannot read: NineSquares/NineSquares.java
1 error
I saved it as a text file inside a folder called NineSquares. The text file is NineSquares.java. What is the problem?
Daniel
-
Excellent Article -- Helped me a lot
2003-12-23 09:51:16 anonymous2 [Reply | View]
Excellent Article -- Helped me a lot
I was looking for "practical examples" to help me get back into Java (for fun) after a long hiatus -- as I prefer a hands on approach.
I found this example refreshingly practical, and the theoretical aspects were integrated organically instead of abstractly -- a frustration with many other exercises.
PS. Had no problems compiling and running (other than the usual --the terminal 'debugging info' pointed out my errors and they were easy enough to figure out) in OSX 10.2.8 on a TiBook.
PPS. Used JEdit as an editor for this -- which I recommend -- it makes it easy to jump back and forth between text files. The Project Builder can be a confounding maze of menus for a newbie where it is easy to make the wrong choices before you even get started.
Thanks very much for this.
-
Back to the Future
2003-12-14 00:51:31 papadog65 [Reply | View]
Thanks for your interesting Java examples. This is my first foray back into Java since it "died" on OS 8 several years ago.
I worked on a Unix project once a few years ago but have forgotten most of it; using Terminal brought back some of those old feelings! Quite a switch from the old MRJ Tools and Ant on OS 8.
About the only problems I had were in cutting and pasting the 1st example into BBEdit (it didn't like whatever occupied what should have been leading whitespace in some of the lines). And, of course a few typos of my own from then on.
I also got some javac errors when I tried compiling multiple programs independently, until I just used the form of ~NineSquares/*.java which automagically did its thing. I'm still a Mac OS X newbie and am starting over with Java and very surprised about not having to wrestle with packages and classpaths as I did on the older system. Perhaps that will come later?
The progression of refactorings was a lesson in itself. It was quite an insight, having been a mainframe procedural programmer for so many years (yeah, I'm still struggling with OOP concepts).
Anyway, thanks again. Great article. Whets my appetite to get back into Java in the future, especially on the OS X platform.
-
nice app but isn't cross platform
2003-10-24 03:33:43 anonymous2 [Reply | View]
doesnt' responds as expected on linux
-
system tray for Mac Os
2003-06-30 19:15:42 anonymous2 [Reply | View]
Dear sir,
i want to develop the java application to display the system tray icon in Mac OS.
For Microsoft window, creating the system tray icon is quite easy to do using C++.But i m not sure how to start to create it for Mac OS...
Can u help me....
Thanks
-
really great!
2003-04-11 00:59:33 anonymous2 [Reply | View]
i dont even had got any problem...was great(im using Eclipse)
-
Try banging your head against the wall for a bit
2003-02-07 17:46:04 anonymous2 [Reply | View]
I couldn't get it to run either the first dozen times. For some inexplicable reason after a few rounds of getting rid of the old .class files and retyping parts of the code that weren't being executed and rebuilding, it started to work. I then had a similar problem with responding to the MouseEvent. Several (clean, retype and recompile)s later it started to work. I didn't find any bugs or typos it just started working. Managed to get all the way though it but I am slightly balder now because of it.
I really hope this is stab it the dark method is not typical of Java development. What kind of tools are there for debugging? There would obviously be something that comes with an IDE so using a generic text editor can be a problem, but there must be some cli tools. -
Author's response
2003-02-10 07:45:37 Daniel H. Steinberg |
[Reply | View]
It is most likely a problem of packaging. It matters where you put your .java files and from where you do the compiling and running. This example has been used (since it appeared here) in intro classes without problems exactly as it's written. Here are the keys that you may have missed. First, all of the files begin with the package statement "package NineSquares". This means that all of the .java files are inside of a directory with the name "NineSquares". The case must match exactly. Second, your compiling and running of the files must happen from outside of the NineSquares directory. For example the file EachSquare.java is inside of NineSquares. If you try to compile it from inside of NineSquares using "javac NineSquares/EachSquare.java" then the compiler looks for a directory named NineSquares inside of the directory named NineSquares. Inside of this second NineSquares directory it is looking for EachSquare.java.
I don't understand your last comments. My article used cli tools for the running of the java. I stayed away from ProjectBuilder because it is not very good at dealing with packages and tends to be hard for beginning Java programmers for this reason. As for debugging, since adopting test first programming a year and a half ago, I have not found myself in a debugger since.
Best, Daniel
-
Also having trouble with first page
2002-09-24 08:17:22 anonymous2 [Reply | View]
Running 10.1.5 with December 2001 dev tools. First application compiles fine, but
[ghiscpc7:~/java/ninesquares] hanley% javac NineSquares.java
[ghiscpc7:~/java/ninesquares] hanley% java NineSquares.NineSquares
Exception in thread "main" java.lang.NoClassDefFoundError: NineSquares/NineSquares
A lot of people seem to be having this trouble. I tried fooling around with the classpath stuff, but I don't think that's it. Perhaps the author could comment on the problems a few of us seem to be having? -
Author's response
2003-02-10 07:38:05 Daniel H. Steinberg |
[Reply | View]
Using what you have done. You created a directory called ninesquares inside of which you create a file called NineSquares.java. The first line of NineSquares.java should read "package ninesquares;" The case must match the name of the directory -- the package structure and the directory structure must match. To compile this file you need to be outside of the ninesquares directory. You can compile it with the command "javac ninesquares/NineSquares.java". According to your listing you have tried to compile it from inside of the ninesquares directory.
Once you have compiled it (again continuing with your directory structure) you then must run it from outside of the ninesquares directory with the command "java ninesquares/NineSquares". This command effectively says look inside of the ninesquares directory and run the NineSquares.class file's main method.
Daniel
-
Aqua versus Swing
2002-06-28 22:44:02 hobbs_dexter [Reply | View]
Apple did a fantastic thing with Mac OS X but they kinda let Java down. Most java apps look miserable or even cease to function in Mac OS X.
Aqua is beautiful but I would prefer the Swing look and feel because it is platform neutral. At least Apple could let you choose whether to run Aqua components or Swing components.
The way it stands about 99% of applets and applications have to be re-written to use Aqua. Yuk!
PS: great tutorial David!
PS2: i just ran NineSquares on Win2K and Linux. they are identical. only the Mac is crippling Swing. Apple outta let swing do its thing!
-
Package Problem
2002-05-17 11:14:50 alex_tea [Reply | View]
I too have a problem with Packages. I'm running OS X 10.1.4 on a Sawtooth G4. if i comment out the "package NineSquares;" on all lines it works fine. if not i get the following errors when compiling the documents:
NineSquares.java:5: cannot resolve symbol
symbol : class MainFrame
location: class NineSquares.NineSquares
new MainFrame();
^
1 error
MainFrame.java:12: cannot resolve symbol
symbol : class EachSquare
location: class NineSquares.MainFrame
getContentPane().add(new EachSquare());
^
1 error
EachSquare.java compiles ok.
I expect this has to do with classpaths although i have yet to find a good resource on setting up classpaths in os x and what they should lead to. I followed this tutorial as i am having trouble compiling a project for college which uses a package of classes built by my tutor for use in the module. i set the classpath to point at the zip file and it wont work. however, it compiles fine on a pc. perhaps there should be an o'reilly tutorial on classpaths.
-
package problem
2001-12-05 11:23:52 patrickr [Reply | View]
When I try to compile with the statement
package NineSquares;
at the top of the files
EachSquare.java compiles
but when I try to compile MainFrame.java
here is what I get
------------------------------------------------------
[localhost:~] patrickr% javac NineSquares/MainFrame.java
NineSquares/MainFrame.java:11: cannot resolve symbol
symbol : class EachSquare
location: class NineSquares.MainFrame
getContentPane().add(new EachSquare());
^
1 error
[localhost:~] patrickr%
--------------------------------------------------------
When I remove the line
package NineSquares;
All is well and the files all compile and I can complete the application.
It seems that I cannot make packages on my setup.
I am using masosx.1 on an imac with developers tools x.1 installed.
-
Java - Terminal & Project Builder
2001-09-25 23:35:48 gsheldon [Reply | View]
Daniel
Thanks for your tutorial. Despite all of my Java books I learned some very valuable tips from the article. It was cool learning how to use the Terminal to compile and run programs, especially since many of the books I have were for non-Mac java environments. The Terminal isn't that foreign to Hypercard programmers who use the Message Window. Also, I appreciated the way you showed how to integrate several files to run a program. This area is still a bit confusing to me and it would be great to have other examples.
Also, the program compiled and ran just fine with the Terminal but I created the same files in Project Builder and it compiled but would not load? Any thoughts on this.
Thanks GtrGeo
-
Not found
2001-08-19 10:57:39 boscarol [Reply | View]
You say
Use the JavaDocs that come with the Java installation. You'll find them at: file://localhost/System/Library/Frameworks/ JavaVM.framework/Versions/A/Resources/English.lproj /Documentation/Java/index.html.
But I don't find this index.html. In Versions/A/Resources I find only Info-macos.plist, MacOS (a folder) and version.plist.
Have I to install something special?
Thank you
Mauro Boscarol
-
Java Docs
2001-08-20 08:15:19 Daniel H. Steinberg |
[Reply | View]
Mauro,
Try navigating with the Finder. In my installation I find the docs in the following directory: Mac OS X/Library/Java/Home/docs/. When I double click on index.html it takes me to the path I listed above. They may be in a different location on your machine.
One way to locate them would be to search for some Java specific doc such as JMenuItem.html and work backwards two layers. That file will sit inside of <...>/docs/javax/swing. You can then navigate up to the docs directory and look for index.html.
Best,
Daniel -
Not found
2001-10-17 20:04:18 shideg [Reply | View]
Hi Daniel.
I'm afraid I do not have a docs directory in the path you listed. I only see:
bin
JSSE Copyright.rtf
JSSE License.rtf
lib
src.jar
Nor can I locate the specific doc JMenuItem.html as you suggested. It looks like I don't have documentation on this system.
Do I have an incomplete installation of Java? I updated to Mac OS X 10.1 from 10.0.4, and I also installed the new Developer tools on top of a previous installation of older versions.
Did I do something wrong?
Thanks for any help you can give me. If you'd rather take this off the feedback section, you can e-mail me directly at hideg@mac.com.
Thanks.
++Steve Hideg -
Java Docs
2004-10-12 14:39:37 jimb01 [Reply | View]
I'm having the same problem. very frustrating. I have Java 1.4.2 and can't find the doc. I tried the Address, and managed to get down to "Resources". But, alas, English.1proj" was not there.
Also, could not find "JMenuItem.html" -- in the same boat as Steve - but sinking.
I'm a newbie to Java, and development on the Mac.
Thanks for any help... Jim
-
Can't get past first page....
2001-08-17 22:08:34 kilishan [Reply | View]
When I try to compile the simple main() function, it gives me the following error:
Exception in thread "main": java.class.NoClassDefFoundError: //NineSquares
I have updated to the latest JDK. -
Can't get past first page....
2001-08-20 06:41:51 fatbob [Reply | View]
the command should be (assuming you've followed the article by naming your package 'NineSquares'):
~/>java NineSquares.NineSquares
that is <package name>.<class name>
make sure that the class you're running is in your classpath either by the top level of the package being in the current directory or setting it on the command line via the -cp flag eg.
~/> java -cp path/to/ninesquares NineSquares.NineSquares
or setting the environment eg.
~/>export CLASSPATH=path/to/ninesquares






[Session started at 2007-01-26 15:22:14 -0800.]
Unable to access jarfile macdevcenter_java.jar
The Debugger has exited with status 1.The Debugger has exited with status 1.
Also in the Build Results window:
Compiling Java source files (2 errors)
'{' expected
'}' expected