Slashdot Mirror


The JFC Swing Tutorial

Long-time reviewer Jason Bennett has sent a review of the official Sun tutorial on the new Swing GUI package called, not surprisingly, The JFC Swing Tutorial. If you are learning Java, use Java or want to learn Java, click below to learn more about this new book. JFC Swing Tutorial author Kathy Walrath & Mary Campione pages 953 publisher Addison Wesley, 06/1999 rating 8/10 reviewer Jason Bennett ISBN 0201433214 summary The official Sun tutorial on the new Swing GUI package Background

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
    1. About the JFC and Swing
    2. Compiling and Running Swing Programs
    3. Running Swing Applets
    4. A Quick Tour of a Swing Application's Code
  • Features and Concepts
    1. Components and Containment Hierarchies
    2. Layout Management
    3. Event Handling
    4. Painting
    5. Threads and Swing
    6. More Swing Features and Concepts
    7. The Anatomy of a Swing-Based Program
  • Using Swing Components
    1. A Visual Index to Swing Components
    2. The JComponent Class
    3. Using Top-Level Containers
    4. Using Intermediate Swing Containers
    5. Using Atomic Components
    6. Solving Common Component Problems
  • Laying Out Components
    1. Using Layout Managers
    2. Creating a Custom Layout Manager
    3. Doing Without a Layout Manager
    4. Solving Common Layout Problems
  • Using Other Swing Features
  • Writing Event Listeners
    1. Some Simple Event-Handling Examples
    2. General Rules for Writing Event Listeners
    3. Listeners Supported by Swing Components
    4. Implementing Listeners for Commonly Handled Events
    5. Summary of Listener API
    6. Solving Common Event-Handling Problems
  • Working with Graphics
    1. Overview of Custom Painting
    2. Using Graphics Primitives
    3. Using Images
    4. Performing Animation
    5. Solving Common Graphics Problems
  • Converting to Swing
    1. Why to Convert
    2. How to Convert
    3. Conversion Resources
    4. Solving Common Conversion Problems
  • Appendices
    1. Code Examples
    2. Reference
  • Index

19 of 92 comments (clear)

  1. My thoughts on Swing by Bryan+Ischo · · Score: 2

    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).

    1. Re:My thoughts on Swing by jilles · · Score: 2

      "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."

      Ok, how would you solve the problem of designing a cross platform GUI framework? AWT wasn't really cross platform since it used native GUI components. Yet it did provide a nice abstraction from the graphical subsystem. What they did with swing is kick out the native components and provide cross platform replacements.

      If you really dive into the framework, you must admire its design. Like you said it solves a lot of problems. And it does so in a rather elegant way.

      Swing is a large complex framework that was developed in a short timespan (the final version is only a year old). The sun developers added a lot of functionality. What they will probably do the coming time is optimize the framework. I expect that JDK 1.3 will be mainly bugfixes and optimizations.

      --

      Jilles
    2. Re:My thoughts on Swing by jilles · · Score: 2

      "On my mac, Swing simply doesn't look (even with their Mac PLAF) nor feel like a mac application."

      The explanation for this is quite simple: the apple implementation of Java sucks.

      "You cannot have a cross-platform GUI when you create the widgets in your code"

      I'm a bit confused about this statement. I hope you don't mean that its impossible to recreate the same GUI on different platforms because that is exactly what swing does.

      Later on you mention that it is impossible to entirely incorporate the look and feel of one platform without violating the look and feel on other platforms. You're right, so what? The goal of pluggable look and feel is not to copy into every detail the look and feel of a specific platform but to be able to customize the applications look and feel without touching the application. A nice application of this is to immitate the look and feel of different platforms to provide users with a familiar looking GUI. A more interesting advantage is that it enables application developers to give a unique look to their applications.

      "cross platform" for Java programs simply means that a program works on every platform that implements the VM. Of course you can't make all platform specifics crossplatform (that's a contradiction). It's silly to claim that and nobody is doing that.

      "NeXTstep and MacOS X Server provide an at least as powerful framework as Swing, but is much faster and doesn't have those inconsistencies."

      Irrelevant because you need apple hardware to run it. Nice design but not crossplatform (in both our interpretations of this term).

      --

      Jilles
    3. Re:My thoughts on Swing by greenrd · · Score: 2
      A long call stack doesn't necessarily matter in terms of performance, because a good optimising JIT compiler can in principle do lots of inlining so that those calls and returns don't actually happen, they just get inferred from the original .class file if and when a stack trace needs to be printed (which is very rare in the big scheme of things).

      Of course, that long call stack might mean it's doing things very inefficiently, or it might mean merely a very fine-grained level of modularity (you're bound to see a lot of methods being traversed that way), which to me speaks of a good, extensible design, not a bad one. Sometimes it's the former, obviously (I've found code which is orders of magnitude too slow, probably because of lack of cacheing of results), otherwise Swing wouldn't be so slow, but sometimes it's the latter.

      Sun really haven't invested much effort in optimising Swing yet, they've concentrated on server-side which is hot right now, and they know of course that Moore's Law will do some of the work for them. One big problem is that Swing currently takes almost no advantage of any kind of graphics acceleration. Try switching Windows into vanilla 640x800 VGA mode and see how the graphics noticeably slows down now that it can't use acceleration. I think once they fix this, most of the complaints about speed (on Win32 anyway) will go away.

  2. Your logic astounds me. by joss · · Score: 2

    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/
  3. Not recommended. by joss · · Score: 2

    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/
    1. Re:Not recommended. by luge · · Score: 2

      like the score 0 AC below me mentioned, Sun books can be very critical of Java. Core Java is on the desk right in front of me, and there are several passages where the author basically says "What the hell were they thinking?" Instances of poor design, poor implementation, and areas where some Sun employees clearly didn't know what the hell the other employees were doing. My point? You can trust Sun books- if Core Java is any indication, they are very blunt about the shortcomings in Java. As far as the language itself, I agree that implementation may be completely screwy- that is why the performance stinks. And I'd much prefer it to be GPL'd. But Java is pretty much ubiquitous- and I can compile it on my box and know that it will run on virtually every machine in the universe. That is what Sun advertised, and particularly with Swing, that is what they have delivered. Until something else delivers the ease of programming and the complete and utter portability, I'll stick with Java. ~luge
      P.S. Moderators, don't knock me as redundant unless you knock up the AC who said this first.

      --

      IAAL,BIANLY

  4. GUIs, code and how not to do it. by Jules · · Score: 2

    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.

  5. Re:Once again ... by pspeed · · Score: 2

    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.
  6. Re:Will book solve Swing's slowness? by jilles · · Score: 2

    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
  7. Re:Will book solve Swing's slowness? by jilles · · Score: 2

    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
  8. why buy the dead tree version of a website? by jilles · · Score: 2

    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
  9. Re:All good by jilles · · Score: 2

    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
  10. Re:Will book solve Swing's slowness? by jilles · · Score: 2

    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
  11. Re:Is Swing important anymore? by jilles · · Score: 2

    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
  12. Re:Will book solve Swing's slowness? by jilles · · Score: 2

    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
  13. Re:Will book solve Swing's slowness? by jilles · · Score: 2

    "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
  14. Re:IF you're after speed, forget Java. by rcromwell2 · · Score: 2


    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)

  15. Once again ... by aUser · · Score: 2

    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.