|
comp.lang.java.gui FAQ
Version: $Revision: 1.9 $
Posting-Frequency: monthly
Copyright: Copyright (c) 2003, 2004 Thomas Weidenfeller
Maintainer: Thomas Weidenfeller.
See below for mailing instructions.
Last-modified: $Date: 2004/04/15 12:45:30 $
N.B. This is a reproduction of the original c.l.j.g. FAQ, the original and most up to date version can always be found through the comp.lang.java.gui FAQ thread. Table of Contents
1 IntroductionQ1.1 What is this, and what does it contain?This is the FAQ for the comp.lang.java.gui newsgroup. It mostly consists of a selection of pointers to resources regarding Swing and AWT programming in Java. Q1.2 There are so many Java FAQs. Which is the right, official one?There is probably not THE FAQ. Everyone can start an FAQ, and many have done so. See it as some benefit. There is a lot of information out there. Note, however, that there is at least one so-called "Java FAQ" which just recycles postings to the comp.lang.java.* newsgroups and distributes them as a newsletter and as a book. You might consider searching an archive of the groups instead. For a list of other FAQs and FAQ lists :-) see http://mindprod.com/jgloss/faqs.html Q1.3 I noticed broken links in the FAQ. Don't you verify them before publishing?No, I don't. I rely on feedback from readers. Also, links might break at any time, e.g. just seconds after a link has been verified. Q1.4 What is AWT?AWT (The Abstract Window Toolkit) is Sun's first Java GUI toolkit. It is rather limited and uses the native GUI components of the operating system. Unless you have to support an old VM, Swing is usual the better choice for a Java GUI toolkit. Q1.5 What is Swing?Swing is Sun's second attempt at a Java toolkit. It is rich in functions and widgets, and is considered the standard Java GUI toolkit. Nowadays it is bundled with the Java 2 Standard Edition. Most parts of Swing are written in Java, especially most of the GUI components. Swing uses some parts of AWT in order to gain access to the native GUI system for event handling and top-level containers. It is build on AWT's lightweight component framework. Q1.6 What is SWT?SWT is an alternative GUI toolkit from IBM. Unlike AWT and Swing, it is not part of the Java 2 Standard Edition. You have to obtain it separately for the platforms you want to support (it uses a native library). 2 The Top 5 QuestionsQ2.1 My GUI freezes or doesn't update. What to do?Most likely you are blocking the event dispatching thread (EDT). Offload time-consuming tasks from your event listeners to separate threads. You can do the necessary implementation by hand, or you can use existing frameworks like the SwingWorker class from Sun. See the series of articles in http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html For some special cases you can give paintImmediately() a look. See http://java.sun.com/products/jfc/tsc/articles/painting/index.html for some information about using paintImmediately(). Q2.2 How do I update the GUI from another thread, e.g. once I have offloaded a time consuming task from the EDT to another thread?See the javax.swing.SwingUtilities.invokeLater()and javax.swing.SwingUtilities.invokeAndWait()methods. Usually you want invokeLater(). Again, see http://java.sun.com/products/jfc/tsc/articles/threads/threads1.htmlfor more details. Q2.3 I have arranged all my widgets nicely on a window. Then I changed the OS / Java version / font / PLAF. Now everything is broken. What's going on?This sounds as if you don't use layout managers, but instead hard-coded component sizes and widgets. If you want to avoid this problem, there is no way around using layout managers, or implementing your own geometry management from scratch. Q2.4 My graphics on a Canvas/JPanel/JComponent, etc. gets corrupted, or I get a null pointer exception when trying to draw. How can I avoid this?Do not use Component.getGraphics(). Instead, subclass and override the paint() (AWT), or paintComponent() (Swing) method. Component.getGraphics() simply can't work. Java uses a callback mechanism for drawing graphics. You are not supposed to "push" graphics information into a component using getGraphics(). Instead you are supposed to wait until Java calls your paint()/paintComponent() method. At that moment you are supposed to provide the Component with the drawings you would like to do. This mechanism is necessary so Java can support graphics systems which don't remember window contents when it is obscured (e.g. overlayed by another window). When the window becomes visible again, such graphics systems have to ask the application to reconstruct the window content. Therefore, paint()/paintComponent() is supposed to be the memory of a component. getGraphics(), however, doesn't have any recollection of previous drawing operations. So once a drawing done via getGraphics() is lost, it can't be reconstructed. There is nothing in there that stores the old drawing data, and there is nothing in AWT/Swing which informs getGraphics() to do some re-drawing. In addition, there are situations where Component.getGraphics() simply returns null. This is a defined behavior of the method. And finally, most users of getGraphics() forget to dispose the Graphics object after usage. See http://java.sun.com/products/jfc/tsc/articles/painting/index.htmlfor more information. Q2.5 How can I make a transparent or non-rectangular window?You can't in a good, platform independent way. Although particular Java components can be 'transparent', they will always be contained inside a rectangular root component that is not transparent. One hack is to take a snapshot of the underlying screen region using java.awt.Robot.createScreenCapture(rectangle). And then using that snapshot as a background image for the window. If the background changes, the illusion is gone. An alternative for applets can be found here: http://java.sun.com/docs/books/faq/src/app/MatchBackgroundExample.html[I also remember to have seen a solution using JNI for windows. Pointers are of course welcome.] 3 Window / [J]Frame / [J]Dialog (Top-Level Containers)Q3.1 How can I make sure a window is always on top of all other windows using AWT or Swing?Before Java 1.5 you couldn't: AWT and Swing didn't provide this feature. All you could do was to use a (modal) [J]Dialog, and make sure the [J]Dialog is provided with the correct parent/owner in the constructor. Since Java 1.5: Window.setAlwaysOnTop(), which is inherited by the other top-level containers like JFrame. Q3.2 How can I (de)iconify a window?Before Java 1.2 you had to revert to native calls. Since Java 1.2 you can use [J]Frame.setState(). Since Java 1.4 you can use [J]Frame.setExtendedState(), too. setExtendedState() provides more features than setState(). Q3.3 How can I replace/remove the icon in the title bar (window decoration) of a [J]Frame?Use setIconImage(). To revert to the platform's default icon use:
frame.setIconImage(null);
On some platforms this might remove the icon. Alternatively you can try
a transparent Image if you don't want to have an icon.
Q3.4 How can I replace the icon in the title bar (window decoration) of a [J]Dialog?There is only a partial solution to this problem, and it is not recommended. A dialog gets its icon from its parent frame. You can create a dummy frame, set the icon of that dummy frame, and use it in the constructor of the dialog as the dialog's owner:
JFrame dummy = new JFrame();
Image icon = ...
dummyFrame.setIconImage(icon);
JDialog dialog = new JDialog(dummy);
However, this is dangerous. Certain GUI behavior depends on a correct [J]Frame (parent window) <-> [J]Dialog (child window) relation. Introducing a dummy parent breaks this relation. Things which can go wrong include (de)iconising of all windows of an application, and ensuring a modal dialog is always placed on-top of the main window. Q3.5 My modal dialog goes behind the main window. How can I make sure it is in-front instead?Make sure you have properly set up the 'owner' of the dialog in the dialog's constructor. Don't use null, and don't use a dummy frame (to set the dialog's icon). Q3.6 How do I get the screen size? How Do I center a window on the screen?Manually, pre 1.4: Use java.awt.Toolkit.getDefaultToolkit().getScreenSize() to get the screen size, and do the math:
import java.awt.*;
Dimension winSize = win.getSize();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
win.setLocation(
screenSize.width / 2 - winSize.width / 2,
screenSize.height / 2 - winSize.height / 2
);
Since 1.4:
Window.setLocationRelativeTo(null);
4 Graphics and PaintingSee the "The Top 5 Questions" section, too.Q4.1 What is the equivalent of AWT's Canvas in Swing?JPanel, if you want to have a "complete" component with a UI delegate which handles opaque settings (if paintComponent() is correctly overridden). JComponent if you intend to always draw every pixel in the area of the component (and break the opaque attribute API contract). If you need to have your own special key and mouse processing, you might also want to start with JComponent and create your own UI delegate. You could even start higher up in the inheritance chain. java.awt.Component is lightweight since Java 1.1. However, you will not get Swing additions like double-buffering. If this is all Greek to you, use JPanel. And remember, if you use JComponent or JPanel, override paintComponent(), not paint(). Q4.2 How do I generate some charts / plots in Java?If you want to do the drawing in Java, consider using a chart drawing library. E.g. http://www.jfree.org/jfreechart/index.html gets recommended often. The web site also has a list of other chart libraries. If you just have to plot some (scientific) data, and if you can live with an external C program, consider using gnuplot http://www.gnuplot.info/ Use System.exec() to pipe the plot commands and data into gnuplot, or just write the data to a file and use gnuplot separately. Q4.3 I want to write a diagram editor. How to start?Consider using a framework like http://www.jhotdraw.org/for a start. You also might want to familiarize yourself with many of the design patterns in
Gamma, E.; Helm, R.; Johnson, R.; Vlissides, J.: Design
Patterns: Elements of reusable object-oriented Software.
Addison-Wesley professional computing series. Brian W.
Kernighan, Consulting Editor. Reading, MA: Addison-Wesley,
1994.
And (if you manage to find documentation), the early work on UniDraw and IDraw by Vlissides is also interesting (in C++). Q4.4 How do I draw lines between JLabels on a JPanel?You are apparently trying to draw a graph by using normal widgets to draw the nodes of your graph. This is not a good idea. Consider using the Java 2D API (nowadays part of J2SE) to draw the complete graph. Have a look at java.awt.geom for predefined shapes. Also check out Sun's 2D Programmer's Guide (see the "Resource" section of this FAQ). Q4.5 I need to draw a tree. How?This seems to be a common homework question, so please have a look at the "Which topics are not welcome in the newsgroup?" to understand why this answer is intentionally vague. If the fixed layout of JTree suits your needs, you could start reading the JTree API documentation. Or you could use a simple (recursive) algorithm. E.g
x(node) = K * level(node), and
y(node) = M * inorder_rank(node).
gives very ugly trees, but trees. If this doesn't get you started, ask your professor or tutor for more hints. Consult your text book about (inorder) tree traversal, and consult http://home.earthlink.net/~patricia_shanahan/beginner.html 5 Other Common QuestionsQ5.1 My GUI has rendering problems when the JMenu opens over my top Panel ...Swing (JMenu) and AWT (Panel) components do not mix well. See http://java.sun.com/products/jfc/tsc/articles/mixing/index.htmlfor things you have to pay attention to. Q5.2 I append text to a JTextArea. How do I ensure the text area is always scrolled down to the end of the text?textarea.setCaretPosition(textarea.getDocument().getLength()); Q5.3 How can I do this JavaScript thing on my web site?Java is not JavaScript. Try news:comp.lang.javascript or another suitable JavaScript newsgroup. Q5.4 I changed the data / structure for my JTree, but the display doesn't get updated. What's going on?Most likely, you are directly manipulating the TreeNodes, instead of updating the data via the TreeModel. TreeNodes don't have any means to inform the JTree about changes. This is the job of the TreeModel. If you use DefaultTreeModel, all the event notification mechanisms are already implemented. If you use an own implementation of TreeModel, you need to implement the necessary event firing yourself. Don't call repaint() on the JTree. The JTree painting is not broken. Your event notification is. 6 The NewsgroupQ6.1 What is this newsgroup's charter? What are acceptable topics?The voting for the group with the group's charter passed on 1997-04-10: http://groups.google.com/groups?selm=860665862.3170%40isc.org A longer history of comp.lang.java.* reorganizations can be found in ftp://ftp.isc.org/usenet/news.announce.newgroups/comp/comp.lang.java-reorg Here is an excerpt from the '97 reorg charter (Note, "all groups" refers to all the Java groups from that voting, including comp.lang.java.gui): CHARTER: all groups The normal practice should be that most articles are posted to one single, correct group ONLY. Cross-posting is only appropriate when the problem is hard to categorize or when it legitimately concerns more than one group. Answers should be posted to a single group only once the nature of the problem has been ascertained. Many articles of this sort should go to comp.lang.java.help (only). It is not appropriate to post binary class files or long (longer than one or two screenfuls) source listings on any of these groups. Instead, the post should reference a WWW or FTP site (short source snippets to demonstrate a particular point or problem are fine). END CHARTER. [...] CHARTER: comp.lang.java.gui This unmoderated group is for any and all discussion relating to GUI toolkits or window frameworks in Java. Topics include the AWT, Netscape's IFC, Microsoft's planned AFC, Visix's Vibe toolkit, among others. The newsgroup will also be the appropriate place for discussion of the JDK event model, mouse and keyboard issues, bugs in windowing code, and graphics programming in Java. If it concerns something that can be seen on the screen, it belongs in this group. END CHARTER. One will note the list of ancient Java GUI technologies, and the absence of Swing. It is save to say, that nowadays most discussions are about Swing, plus a few about AWT and Java printing. Q6.2 Which topics are not welcome in the newsgroup?Of course, this question is never asked, but over the time, it has turned out that certain types of postings are not welcome, even if Java related. This includes:
Q6.3 Where can I find an archive of this group?See e.g. http://groups.google.com/groups?group=comp.lang.java.gui Q6.4 What is an SSCCE?Short/small, self contained, compilable, example (source code). It would be best if you provide such short (see the group's charter) example source code in our first request for help. When asked for one, please don't complain that your source code is to large, to tricky, to secret for being cut down to a reasonable size and posted. You have the problem, and you asked in a public forum, so it is in your interest to provide the requested information. For more information about hacking some example code together, go to http://www.physci.org/codes/sscce.jsp Q6.5 Why don't people like top-posting? What is top-posting?See the following Question & Answer (well, Answer & Question) section:
A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on Usenet and in e-mail?
-- Common Usenet signature
Q6.6 Is there more about posting to newsgroups and asking questions?Yes, see e.g. http://www.catb.org/~esr/faqs/smart-questions.html http://www.yoda.arachsys.com/java/newsgroups.htmlfor making the most out of a newsgroup (ignore the hacker slang) [The author of the first document has requested a notice that he is not a help desk for your problems]. Also see the newsgroups: news:news.newusers.questions news:news.answers And RFC 1855. E.g. at ftp://ftp.rfc-editor.org/in-notes/rfc1855.txt http://www.faqs.org/rfcs/rfc1855.html 7 ResourcesThere are many good on-line resources regarding Java GUI programming out there. The following list is limited by intention to resources which get recommended often on c.l.j.g, including resources from regulars. 7.1 Sun's Java Web SiteSun's Swing Example Tutorial (previously Quick-Start Tutorial): http://java.sun.com/docs/books/tutorial/uiswing/mini/index.html The complete Sun's Swing Tutorial: http://java.sun.com/docs/books/tutorial/uiswing/index.html Sun's Swing Connection (TSC) (Swing developer's site). Note: Sun is currently doing some heavy restructuring of the site. Apparently, parts have already ended up at http://www.javadesktop.org, while others are currently missing: http://java.sun.com/products/jfc/tsc/index.html The TSC article index (Swing architecture, Swing and threads, painting architecture, etc.): http://java.sun.com/products/jfc/tsc/articles/ Or, at least for now, the article index is at http://www.javadesktop.org/tsc/index.html 7.2 IconsIt is suggested to check the licenses of each icon collection before using them in any products. Several of the following packages come with open source / free software licenses. Sun's well hidden set of Icons for Swing's Metal LnF: http://developer.java.sun.com/developer/techDocs/hi/repository/ More icons: http://sourceforge.net/projects/icon-collection/(the link to javalobby.org on that page is broken) The Ximian Open-Office icons (very nice): http://developer.ximian.com/themes/icons/ooo-icons.htmlGnome icons: http://tigert.gimp.org/gnome/gnome-stock/SVG BlueSphere Icon Theme: http://svgicons.sourceforge.net/KDE Icons: http://www.buzzard.org.uk/jonathan/kde-icons.html 7.3 Misc. Examples, Tips and TricksA collection of examples for doing nice things with Swing components (some are a little bit outdated): http://www.physci.org/codes/tame/Originally from http://www2.gol.com/users/tame/swing/examples/SwingExamples.htmlwhich is now off-line. Christian Kaufhold's Java and Swing info (including JTable info): http://www.chka.de/ Jeanette's notes (including JTable remarks): http://www.mycgiserver.com/~Kleopatra/swing/swingentry.html Marco Schmidt's Java resource page (Java imaging information) http://www.geocities.com/marcoschmidt.geo/java.html Karsten Lentsch's company web page: http://www.jgoodies.com/ 7.4 Style GuidesJava Look and Feel Design Guidelines: http://java.sun.com/products/jlf/ed2/book/index.html Java Look and Feel Design Guidelines: Advanced Topics: http://java.sun.com/products/jlf/at/book/index.html 7.5 SDK DocumentationGUI Information in the SDK documentation (commonly overlooked): See your local SDK installation, or Abstract Window Toolkit (AWT) http://java.sun.com/j2se/1.4.2/docs/guide/awt/index.html Swing http://java.sun.com/j2se/1.4.2/docs/guide/swing/index.html 2D Graphics and Imaging http://java.sun.com/j2se/1.4.2/docs/guide/2d/index.html Image I/O http://java.sun.com/j2se/1.4.2/docs/guide/imageio/index.html Print Service http://java.sun.com/j2se/1.4.2/docs/guide/jps/index.html Input Method Framework http://java.sun.com/j2se/1.4.2/docs/guide/imf/index.html Accessibility http://java.sun.com/j2se/1.4.2/docs/guide/access/index.html Drag-and-Drop data http://java.sun.com/j2se/1.4.2/docs/guide/dragndrop/index.html Swing Examples in the SDK: See the directory demo/jfc in your Java SDK installation. 7.6 More SwingSwing class-hierarchy chart http://www.holub.com/goodies/java.swing.html jGuru Swing FAQ http://www.jguru.com/faq/Swing CodeGuru Swing Examples http://www.codeguru.com/java/Swing/index.shtml 7.7 Online MagazinesJavaWorld has regular GUI articles. The magazine closed shop on 2004-01-02, but was re-launched March 2004. http://www.javaworld.com/ 7.8 Java 2D APIThe Programmer's Guide http://java.sun.com/j2se/1.4.2/docs/guide/2d/spec/j2d-bookTOC.html 7.9 AWTSun's AWT FAQ http://java.sun.com/docs/books/faq/faqawt.html 7.10 Java 3D APIThere is a separate newsgroup. see news:comp.lang.java.3d http://groups.google.com/groups?group=comp.lang.java.3d 7.11 General JavaThe Java Tutorial: http://java.sun.com/docs/books/tutorial/ All kinds of tutorials: http://developer.java.sun.com/developer/onlineTraining/ Roedy's Java Glossary: http://www.mindprod.com/jgloss/jgloss.html 7.12 More?Q7.12.1 But I need more, more, more!Learn how to use a search engine like http://www.google.com 8 Improvement SuggestionsPlease mail suggestions, corrections, updates, etc. to the account "cljg_faq" on the "gmx.de" site. Your "Subject:" line must contain the string
[cljg]
somewhere, including the square brackets. Otherwise your mail will be discarded automatically. In addition, the address is heavily spam-protected. So if you mail from a spam-invested network, there is little chance to reach me. Your alternative is to post to c.l.j.g. If you suggest a new entry, please also provide the answer, not only the question. 9 AcknowledgmentsThis FAQ contains contributions and help from: Andrew Thompson, David Postill, Manish Hatwalne |