The JFC Swing Tutorial
I was just finishing up my first year of university when Java burst onto the scene. As those of us who were around then can remember, the hype was intense. Actually, that would be an understatement. You would have thought Java was going to save the world and make your morning coffee all at once. Fortunately, things settled down almost as fast as they began, and Java started on its long road to maturity. In many ways, this book is the culmination of three years of Java maturation. The AWT, Java's original GUI library, has been replaced by a completely new one, Swing, with the release of Java 1.2/2.0. It promises to have more features, be more stable, and generally live up to the platform-specific libraries against which it competes. In many ways, Swing is the hope for Java on the desktop. Of course, you have to figure out all those APIs first....
What's the book about?The JFC Swing Tutorial is the Sun-imprinted official word on how to code for the Swing API (note that this book is also available for free from Sun's web site [see the link in the title above]). Of it's 950 pages, literally the last 300 are source code to all of the examples in the text, while the first 600 delve into every aspect of Swing. As with most tutorials, things start off slow, with a "hello, world!" equivalent, but the difficulty ramps up quickly. There is a (relatively) short section giving an introduction to layouts, painting, and other GUI basics before the real meat of the book begins.
Chapters 12-17 are the heart of the tutorial, and take the reader through every part of the Swing API. This is broken up into top-level containers (frames, dialogs, applets), intermediate-level containers (panels, panes, tool bars), and atomic components (all the buttons, choosers, and menus). There are tables at the end of each section summarizing the various methods, along with their purposes. There are also example summaries, listing where to find the examples that demonstrate the various concepts presented. The section is quite thorough, with plenty of code interspersed through the text.
The final part delves into the other parts of Swing, including layouts, actions, borders, icons, look and feel, and chapters on event listeners, graphics, and converting from the AWT. These chapters continue the structure begun in the middle sections, with many code examples and handy summary tables.
What's Good?Simply put, if you want to know how to do something in Swing, it's probably covered in this book to one extent or another. In fact, you're likely to find that your code has already been written for you to some extent, given the copious examples provided. Even if you cannot find exactly what you want, you can likely piece it together from what is provided. It's also nice being the official tutorial, as you can trust that the authors had decent references whenever they had a question or two. This is the official way to do Swing.
What's Bad?Well, in short, more than I would like. Personally, I'm not well-grounded in doing GUIs. Not to say that I've never done them before, but I've had my struggles in the past. That's one reason I wanted to review this book, as I was hoping to strengthen my skills along the way. Unfortunately, I don't feel like that has happened. Don't misread the title. This isn't a GUI tutorial in any sense of the word; it's a Swing tutorial. The complexity of the text ramps up quite quickly after "hello, world," and if you aren't ready, you'll be lost in the dust. To be honest, I found this to be more of a reference book than a tutorial, at least to the extent that I wouldn't read this book cover-to-cover, but would pull it off the shelf any time I had a Swing question. The examples are thorough and there are plenty of them, but the style and layout do not make for an easy read-through.
So What's In It For Me?Firstly, you have an amazing advantage of being able to try this book out for free. If you're interested, check out the URL and read through a few sections. Make your own review. You can buy it or ditch it at your leisure. Second, don't use this book as a general GUI tutorial. That's not what it is, and trying to use it as such will only frustrate you. If, however, you know GUIs, and you want to learn about all that Swing has to offer, this is an excellent book. You get an entire CD-ROM full of Java code for your use, plus the official Swing reference. Depending on your needs, this book will either be very helpful, or a very heavy paperweight.
Purchase this book at fatbrain.
- Table of Contents
- Preface
- Before You Start
- Getting Started with Swing
- About the JFC and Swing
- Compiling and Running Swing Programs
- Running Swing Applets
- A Quick Tour of a Swing Application's Code
- Features and Concepts
- Components and Containment Hierarchies
- Layout Management
- Event Handling
- Painting
- Threads and Swing
- More Swing Features and Concepts
- The Anatomy of a Swing-Based Program
- Using Swing Components
- A Visual Index to Swing Components
- The JComponent Class
- Using Top-Level Containers
- Using Intermediate Swing Containers
- Using Atomic Components
- Solving Common Component Problems
- Laying Out Components
- Using Layout Managers
- Creating a Custom Layout Manager
- Doing Without a Layout Manager
- Solving Common Layout Problems
- Using Other Swing Features
- Writing Event Listeners
- Some Simple Event-Handling Examples
- General Rules for Writing Event Listeners
- Listeners Supported by Swing Components
- Implementing Listeners for Commonly Handled Events
- Summary of Listener API
- Solving Common Event-Handling Problems
- Working with Graphics
- Overview of Custom Painting
- Using Graphics Primitives
- Using Images
- Performing Animation
- Solving Common Graphics Problems
- Converting to Swing
- Why to Convert
- How to Convert
- Conversion Resources
- Solving Common Conversion Problems
- Appendices
- Code Examples
- Reference
- Index
I have to say I have my misgivings about Swing and about Sun's approach to the GUI aspects of Java altogether.
Swing is *big*, and *complicated*. Looking into its guts give one a strong feeling of "hack upon hack". AWT was bad, complex where complexity wasn't needed in many cases, but Swing is an order of magnitude worse in that arena.
I often get the feeling, when I look through the Swing JavaDocs, that the architects at Sun are trying to solve every possible problem in one framework. I think they would be much better off to focus on getting what they do *right*, as they do it. If you try to solve every possible problem at once, you will inevitably end up doing everything at a lower quality level than if you just focused on the most important problems at hand, and once they are nailed down, go on to bigger things.
One could say that that's what they did with AWT - they got the low level done and then the moved on to a more complicated, complete GUI framework. I would argue that they never got AWT right; instead they threw up their hands and said, "oh well", and then proceeded to build a huge monsterous framework on top of the weak foundation that they had built with AWT.
Consider this: setting a breakpoint in just about any GUI method of your Java Swing program will show a call stack at least a dozen calls, often two dozen calls, deep. To me, that's a very pointed indication of a framework that is too complex for its own good.
The last thing that Java needs is more bloat, because Java is already very sensitive when it comes to getting performance - you can get good performance in Java (nearly comparable to traditional compiled languages) but ONLY if you optimize the hell out of your Java code and keep those call stacks small. It seems that Sun would rather try to solve every single possible GUI problem in one framework than concentrate on making Java small, tight, solid, and fast, which I believe is what they should be doing, because as every Java developer knows, you have to fight tooth and nail to get Java in the same ballpark performance-wise as other languages (but it can be done - Sun is just making it harder and harder by throwing stuff like Swing at us).
I never said that a deep call stack is necessarily a sign of poor implementation. It just USUALLY is. Recursion is an obvious exception (although with a bit more experience you'll realize that recursion does not deserve nearly as much emphasis as it receives in college). Swing isn't using recursion here anyway, it's purely indicative of bloat. Also, the deep call stack wasn't the only reason why I think Swing implementation is bad - I've read a fair amount of the source code and it seems to have been implemented without any consideration for efficiency.
http://rareformnewmedia.com/
I've read this online, and I would have to say you would be out of your mind to buy this book on Swing.
Why - well, it's written by Sun. They aren't allowed to say things like "this method is all fucked up, it fails mysteriously sometimes and when it does work, it's perversely slow, here is the workaround..."
Buy any other book, at least they are allowed to tell you the truth. There are a couple of good ones out there - "The complete guide to swing" (I think - it's at work)
But better yet, forget about Swing altogether.
The design is good, implementation is terrible.
Stick a break point in a callback and check out the call stack - 20 deep, WTF were they thinking.
Save yourselves endless grief and use the only decent LGPL cross-platform toolkit available:
FLTK, it even comes with its own powerful GUI design tool (fluid). You will end up with 1/4 of
the code required by a Swing based implementation and it will be 10x faster.
http://fltk.easysw.com
http://rareformnewmedia.com/
Before you pick up any book on how to build GUIs, you really ought to have a look at Alan Cooper's The Inmates are Running the Asylum. In fact, it ought to be compulsory reading for anybody building any kind of software. It explores concepts such as -- gasp! -- thinking about what the user is likely to need before design and coding, sticking to the original design, and treating prototypes as prototypes and not version 0.5.
Its theories on why all software is crap are refreshing and while it's simplistic in places, it's a book that both PHB's and those who actually do the work can comprehend.
I have all of these Linux programs that are not compatable with Linux. What a crappy operating system. I'm supposed to have a more stable system and I can't even run my new programs on an old version. (sarcasm off)
Write once, run anywhere means that I can write it once and run it on any compatable JVM on any hardware that happens to have a compatable JVM.
Interpretting the sentence as anything else is just ludicrous. It's flamebait of the highest order.
Edu. sig-line: Choose rhymes with lose. Chose rhymes with goes. Loose rhymes with goose.
Comparing? THEN use THAN.
well I still think you are the one doing something wrong. I mean, I have seen several swing apps and have programmed quite a few myself. I found that swing's powerfull features generally are an open invitation to use them which leads to sluggish performance if you don't know what you are doing.
I'm not claiming swing is well implemented at this moment. But if you know how to use it it is usable.
Jilles
whine, whine,
Sigh, once more: the only, repeat only area where java performance is less than desirable is in the GUI/graphics area. In other areas, ranging from palm top applications to servlets developers are quite happy.
The customers of your java applications probably won't care for your graphical applications. What they do care for is the speed with which you develop applications (about twice as fast as in similar OO languages).
Jilles
The swing tutorial is part of the Java tutorial and has been available from www.javasoft.com/tutorial for years now. During this period the tutorial was expanded to cover new API's. It's an excellent resource for Java programmers. Together with the API documentation it is all the documentation you will ever need. The only thing that puzzles me is why somebody would want to use a printed version of these documents. The online version is so much more convenient.
As the reviewer noted, you typically don't read the tutorial from cover to cover. What you do is find some topic you're interested in, read it. Then you click links to related topics, examples or the API documentation. The latter is very hard to do in a paper version.
Jilles
If there's one thing you can do with Swing it is building advanced tools to create GUIs (needless to say that such tools exist). Unlike MFC (which is the underlying architecture for VB), JFC has a very well designed architecture.
Because of this you can do really cool stuff like embedding GUI components in other GUI components. Try building a 'tree-table', that is a tree structure with tables as its nodes, in VB. It's almost trivial to do such things in swing. Needless to say that it is equally trivial to use whatever component you want for the table cells. The only problem I have with this particular example is that it is difficult to find useful applications for it (somebody help me out).
Jilles
True, swing is slow ate the moment. But it has been steadily improving. One of the main reasons for its perceived slowness is that it takes a long time to load the classes. Swing is a very complex framework and thus even simple swing programs load a lot of classes.
As an illustration. Back in the days when swing was still beta, you were better of running swing programs with the interpreter than than with the JIT. The simple reason for this was that a JIT compiler compiles all classes that are loaded, including those that are rarely executed. BTW. I was working on a pentium 133 with 64 Mb in those days. Even though the loading time was very high, the performance after loading was quite OK (again on a pentium 133).
What this anecdote proves is that it's not so much the raw peformance of the interpreter that is causing the bad performance but the dynamic class loading. JIT compilers generally only make dynamic class loading an even more expensive operation.
If I remember correctly it is exactly this problem (slow loading of swing classes) that is being targeted by jdk 1.3 beta. I'm really looking forward to improvements in this area.
If you are interested in how to make your Java programs faster, you should check out this article. It provides an excellent background on how Java manages its objects.
Jilles
netbeans (www.netbeans.com) is a swing app. Actually most java development is either serverside or stand alone client development. If you are doing serverside development you generally don't need a GUI and if you need one swing covers most of your needs. If you are doing client side development, AWT is not good enough because it doesn't provide much functionality and because it relies on native GUI components (leading to all sorts of incompatibilities between platforms). So for both types of applications swing is used often to provide the GUI.
Yes, swing is slow. Yes, it is complex (if you're a pearl/vb/fill in your favorite scripting language -hacker, it's probably too complex for you). But it is also a very well designed framework. For many developers the advantages of the good design outweigh the disadvantages of bad performance.
I heard some people complain it provided too much functionality and that SUN should have focussed on a less ambitious framework. I'm glad they didn't and decided that the design was important. It may take a bit longer for swing to become usable that way but at least it will be really usable when the performance problems are solved.
I get really tired of those folks who stopped reading in 1995 (that's the only excuse for not knowing that java is (successfully) used for other stuff than applets mostly).
Jilles
Gee, I don't know. I've developed several Swing applications (on computers much slower than your 200 Mhz machine) and I can't say I share your experiences. Sure there are certain things like the slow loading and high memory usage of applications that are annoying but generally you can create a decent application if you know what you are doing.
"depending on some data being entered my app"
Read the javaworld main article of this month. It deals with performance problems due to excessive object creation (which probably explains your problem).
Jilles
"Ibm make a wonderful compiler (jikes), and a pretty good jvm but i don't understand why sun doesn't do that job."
SUN can't do all at once. The past few years they have been working really hard designing APIs and implementing them. They don't have time to support every platform. IBM has a nice VM but so far they have failed to implement a good java 2 platform which is annoying.
Both SUN and IBM are working on linux versions of a java 2 vm so something should come out of that. Until that linux is probably not a suitable development platform for Java (unless you like waiting tools to become available that are already available on other platforms). I have full confidence that they will support linux eventually because Linux is becoming increasingly important as a server platform.
Jilles
JPython is written in Java and runs faster in benchmarks than CPython when using the HotSpot JIT. Smalltalk, for a long time, was the king
of slowness.
Perhaps you are unaware of the difficultly of efficiently compiling fully dynamic weakly typed languages like Smalltalk, or Perl5?
If Perl5 sees a bunch of expressions, it has no idea until runtime if $x is a string, floating point, reference, or integer variable. The
situation is even worse for function calls
through a blessed reference where any number
of dynamic mechanisms can cause a different
subroutine to be dispatched. Perl can't inline
like a Java JIT can.
The only way Perl5 could possibly beat a Java JIT is if it had a Smalltalk/Hotspot style JIT compiler that did type-inferencing.
Perl excels at text manipulation and array/hashtable manipulation because those are language primitives which are handled efficiently.
There is no way Perl would beat Java at say, image processing, or ray-tracing. I've been writing Perl for 6 years, and I have written several 30,000+ line apps with it, so I know exactly how it performs.
There is no such thing as one benchmark that decides performance for all languages. Perl will blow away just about even language, even C++ in many cases (inefficient libraries) when it comes to text manipulation, regexp, array slicing, etc.
But Perl won't win on any numerically or graphically intense benchmarks.
I use jEdit on JDK1.2.2 and IBM JDK 1.1.8 as my main editor, because it is much easier to extend than Emacs, and less bloated. The speed is very acceptable, some would say speedy.
Just try writing an editor in 100% Perl or Python without using *any* native components except a bitmap to draw into, and let's see how fast it is. (This is essentially what you get with Swing, since all GUI components are written in Java)
AWT versus Swing and the compatibility and deprecation problem points to the root of the problem: the fact that Java can mathematically not deliver on its promises.
"Write once, run anywhere" not only makes abstraction of the fact that there is already a large installed base of different things, with no realistic cross-upgrade path, it even doesn't work when the whole world would be Java-only already.
Imagine Java does not change, and that there would only be one single release, then it would quickly fail to address new problems, take advantage of new research and development and in time be abandoned for newer technologies.
Imagine Java does change and gets upgraded. That means that it will get new features. If your code takes advantage of these new features, it will not be compatible with the old Java run-time. Therefore, your code does not "run anywhere". It doesn't even run on the previous Java platforms.
Everybody could have seen the AWT to Swing problem coming from day one.
Any technology that makes abstraction of the fact that there is already an installed base, is bound to fail. What's more, any technology that pretends that it will fill all holes, is a scam.
Everyone with half a brain could have seen this problem arriving, from day one, hour one, and minute one. If some idiot comes and tells you that your software will run out of the box on every single platform in the universe, and you believe him, you should check the content of your skull for contamination by animal defecation.
The less someone has a brain, the more that person is bound to be incompetent, and the more he is likely to hype along with the rest. The people who I saw jumping on the Java bandwagon, were already failing in their existing projects, didn't master their old technology and were hoping desperately for something new like Java to make up for their incompetence. I am sorry, but if you can't do the job, not one single technology is going to help.