THE JFC SWING FAQIMPORTANT NOTE: Please update your bookmarks to use http://www.drye.com/java/faq.html. You may need to edit your bookmark by hand. This FAQ is regularly posted in comp.lang.java.gui and the Swing mailing list (swing@eos.dk). It is available on the web at http://www.drye.com/java/faq.html. If you have comments or questions, please send them to Stephen Drye - swingfaq@drye.com. Many thanks to Bill Wake for doing the initial work on getting the web version of this FAQ going and maintaining the first few versions. Recent Edit History: CONTENTS0. Not really Swing, but still FAQs0.1
How do I change the icon of my JFrame? 1. About Swing and the JFC1.1. What is Swing?1.2. What is the JFC? *Changed*1.3. What versions are available? 1.4. Where do I get online information about Swing and JFC? 1.5. What books are available about Swing and JFC? 1.6. Can I run Swing inside a browser? 1.7. What package is Swing in? 1.8. What tools support Swing and/or JFC? 1.9. What is Model-View-Controller? What do design patterns have to do with Swing? 1.10. Swing performance 1.11. Swing and Threads 2. Swing Components2.1.
Why do I get a run-time Error when I add components to a
JFrame/JDialog/JInternalFrame/JWindow? 3. Tables3.1. How
do I put my information in a table? 4. Text4.1. How do I create a JTextField that only accepts numbers, phone numbers, etc.?4.2. How do I use the EditorKit for HTML? 4.3. How can I use the HTMLEditorKit without using a JEditorPane? 4.4. Which version of HTML does the HTMLEditorKit support? 4.5. How do I use the RTFEditorKit? 4.6. How can I use the RTFEditorKit without creating a JEditorPane? 5. Trees5.1. How do I put my information into a tree?5.2. How can I get different icons for my tree nodes? 5.3. How do I load nodes on demand? 5.4. Why won't my folder/directory/etc. TreeNodes draw properly when they don't have any children? 5.5. How do I expand or collapse all tree nodes? 5.6 How can I automatically start editing a TreeNode, for example a new node that the user has added? 6. Undo6.1. How do I support undo in my application?6.2. How do I create a custom UndoableEdit? 7. Accessibility7.1. How do I make a Swing component accessible?7.2. How do I make a non-Swing component accessible? 8. Pluggable Look-and-Feel8.1. How do I get native look-and-feel (instead of the blue/gray "Metal" style)?8.2. Can I run Windows or Mac look-and-feel on other platforms? 8.3. How do I create a UI delegate for my custom component? 8.4. How do I create a new look-and-feel? 8.5 What other look and feels are available? 9. Java 2D9.1. Where can I find information about Java 2D?10. Drag-and-Drop10.1. Where can I find information about drag-and-drop?10.2. Can I make drag-and-drop work with a JTree? 11. About this document0. Not really Swing, but still FAQs0.1 How
do I change the icon of my JFrame? 0.2 How do I get rid of the yellow Applet warning
with my JApplet? You have to sign your applet. See the Netscape, Internet Explorer or Sun Java Plug-in documentation for details on how to do this. *New* 0.3 How do I maximize/minimize a JFrame? How
do I display a JFrame without a title bar? There are new methods on Frame (the AWT parent of JFrame) to do this in J2SDK 1.4. See http://java.sun.com/j2se/1.4/docs/guide/awt/AWTChanges.html#zoom and http://java.sun.com/j2se/1.4/docs/guide/awt/AWTChanges.html#undecorated for details 1. About Swing1.1. What is Swing?According to Sun, the correct name is "JFC Project Swing". Everyone else refers to it as simply "Swing". Swing is a set of lightweight (implemented completely in Java) graphical components. It includes not only the equivalents of AWT components, but also new ones such as table and tree widgets. Swing is a standard part of Java 2 and higher. Swing 1.1.1 is the last version of Swing which will be compatible with JDK 1.1. 1.2. What is the JFC?
There are five versions available at http://java.sun.com/products/jfc:
Websites
Mailing Lists
[Note: I haven't personally reviewed all these books. These came from perusing Fatbrain, Amazon and reader comments]. Available now (alphabetically by author):
Forthcoming:
1.6. Can I run Swing under a browser? OS/2's version of Netscape uses the system's default Java implementation, so Swing works there. All versions of Mozilla (including Netscape 6.0) will behave this way in the future. 1.7. What package is Swing in? 1.8. What tools support Swing and/or JFC?
Design patterns are a literary form that document tried-and-true solutions to design problems. A good starting point is the classic book Design Patterns by Gamma et al. The most famous design pattern is "Model-View-Controller" (also known as "Observer"); this pattern was popularized in Smalltalk. MVC addresses the problem of how to build software for user interfaces. It says to divide the software into three parts: the Model is the basic behavior of the system, independent of any user interface. The View is a presentation of the Model, and the Controller determines how the user interacts with the Model. The View and Controller know about the Model, but the Model is almost unaware of their existence: it merely knows that if it changes, it has to send a message to any registered listener warning it that there have been changes. The easiest place to see this approach is in JTable. You can define a TableModel object (the Model), and tell a JTable (combined View-Controller) to observe that model. When the data changes, the JTable is notified, and it updates its display. Several Views could monitor a single table; the Model notifies them of changes, and lets the Views figure out how to update the display. (A common mistake is to write code to update the TableModel but not send any notifications. This shows up as the changes not being reflected unless you do a resize or force a repaint. Notification is part of the Model's job. DefaultTableModel sends these notifications for you, so see its source code for examples of what to do) There are other design patterns used in the Swing libraries. For example, the "Composite" pattern describes how to handle a containment hierarchy of objects; JComponent implements this pattern. "Decorator" describes how to compose functionality; using CompoundBorder to nest one border inside another uses this approach. Time spent studying design patterns will often help you better understand the design of Swing. 1.10 Swing performance According to the Swing team at JavaOne, Kestrel (Java 2 SDK 1.3) will include a significant number of performance improvements, including improving Java2D's support for common Swing operations. Some of these changes have already made it into Swing 1.1.1 (as of beta 2). See http://java.sun.com/products/jfc/tsc/special_report/performance/performance.html for details. The first performance issue to look at is how Swing is being used. Many methods in Swing are there solely to provide compatibility with the AWT components. These methods tend to be the worst culprits for poor performance, since they hide the component's model from you. Remember that most Swing components are designed to be used by manipulating their model directly. The default model for the component also tends to be a bit slow, since it has no knowledge of what your application is trying to do with the component. If you use your own custom models, you generally see a significant performance improvement. Another trick to remember is to fill your models when they aren't associated with a component. After a model has been associated with a component, it sends Events to the component when it is being modified (for every new item added!). If you add the items to the model when it is not associated with a component, and then associate the model after it is filled the component only gets one Event, notifying it that the model has been added. 1.11 Swing and Threads
2. Swing Components2.1. Why do I get a run-time Error when I add components to a JFrame/JDialog/JInternalFrame/JWindow?In Swing, top-level windows (such as JFrame or JDialog) do not have components added directly to the window. Instead, add them to the content pane like this: myWindow.getContentPane().add(component)2.2. Where are the scroll bars on my JList (or JTextArea)? Swing components don't implement scrolling directly. Scrolling has instead been encapsulated in the JScrollPane class. To get scrollbars on a component, wrap it in a JScrollPane. Instead of: panel.add(component)use panel.add(new JScrollPane(component));Components that implement the Scrollable interface will interact with JScrollPane to configure the scrolling behavior. Components that don't implement Scrollable will get the default behavior supplied by JScrollPane. 2.3. How can I save space in my screens? 2.4. What's the easiest way to create a dialog?
2.5. How can I prevent a window from closing? frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);2.6. Can I mix Swing and AWT components? "Yes, but..." You can mix these components, and it's documented at http://java.sun.com/products/jfc/tsc/swingdoc-archive/mixing.html. However, if it's at all possible, you'll find it much less problematic to convert everything to Swing. (The problem is that AWT components are heavyweight, while Swing components are lightweight, and heavyweight components always appear above lightweight components; this causes difficulty for things like tabbed panes, internal frames, popup menus, etc.) 2.7. How do I use internal frames? Override the JPanel's paintComponent() method and use it to paint the image (which you should store as an ImageIcon). For example: public void paintComponent(java.awt.Graphics g)
{
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
java.awt.Color oldColor = g.getColor();
if (opaque)
{
g.setColor(getBackground());
g.fillRect(0, 0, width, height);
}
if (theImage != null)
{
g.drawImage(theImage.getImage(), 0, 0, this);
}
g.setColor(oldColor);
}2.9. How can I capture KeyEvents for
the Tab key? Override isManagingFocus() to return true, then all key events should be sent to your JComponent. <Christian Kaufhold> 2.10. How can I make a JComboBox
textfield empty? 2.11. Why is my JList/JTree
component sized improperly when I add/remove items from the Model? 2.12. I've added/removed menu(s) from a
JMenuBar. Why isn't the change showing? 2.13 Can I save my UI designs as XML documents? 2.14 How do I change fonts/colors/etc. in my
JOptionPane? The easiest way is to use the JOptionPane constructor where you supply the components that are used to build the JOptionPane. Since you create the components, you can do whatever you want to them before you pass them to the JOptionPane. The constructors to use are any of the ones that take Objects. See the JOptionPane JavaDoc for details on what kinds of Objects you can pass to these constructors.
3. Tables3.1. How do I put my information in a table?Either subclass AbstractTableModel and implement the required three methods, or use a DefaultTableModel (which has a built-in Vector). The methods required by AbstractTableModel are very simple to implement, so subclassing is the preferred method. Using DefaultTableModel requires the expense of copying your data from its native form into the DefaultTableModel. 3.2. Why doesn't my JTable show the column
names? panel.add(new JScrollPane(myJTable))3.3. How do I add and delete rows in a JTable? JTable is only the view onto the real table. To change the table, you need to work with the table model. Each model will have its own methods to do this. If you've subclassed AbstractTableModel, you'll have to create your own add/delete methods. DefaultTableModel contains methods to add/remove/reorder rows. See the next question too. 3.4. Why don't my changes in the table model show
up in the JTable view? 3.5. How do I get different colored table cells?
3.6. How do I load cells on demand? 3.7. How do I get a sorted table? 3.8. How can I get my table to scroll horizontally?
JTable table = ... table.setAutoResizeMode (JTable.AUTO_RESIZE_OFF); JScrollPane pane = new JScrollPane(table);3.9. How can I make sure a certain cell is visible? Get the rectangle for the cell, and scroll to it: JTable table = ... table.scrollRectToVisible(table.getCellRect(row,column,true));3.10. How do I hide a column in a table? Sometimes it's done by setting all the column widths (minimum, preferred, and maximum) to 0 pixels, but this leaves the column in the table. A better approach is to use the removeColumn() method: JTable table = ...
TableColumn deletedColumn = table.getColumn("Column Title");
table.removeColumn(deletedColumn);It can later be added
back into the table by addColumn(). This only affects what column is
shown by the JTable; the model is unaffected.
3.11. How do I detect a double-click on a table
cell? 3.12. How can I change the width a of column of a
JTable? table.getColumnModel().getColumn(index).setPreferredWidth(<width>); table.sizeColumnsToFit(-1);The sizeColumnsToFit() call is no longer needed in JDK 1.3. 3.13. How can I remove a column from a
JTable? TableColumnModel model = table.getColumnModel(); model.removeColumn(model.getColumn(index));3.14. How can I add a column to a JTable? - use DefaultTableModel's addColumn method. - create a new JTable model. - update your own JTable's TableModel (Since your TableModel is a subclass of AbstractTableModel (there isn't a strong reason for it not to be) you just need to call fireTableStructureChanged() when the update is complete). 3.15. How can listen for clicks on a
JTable header? 3.16. How can I display an image in a JTable cell? First make getValueAt() return the Icon for that cell. Then, make getClassForColumn() return ImageIcon.class (Icon.class also works as of 1.3) in your table model. - Philip Milne 3.17. How can I convert from model indices to view
indices (when the user has reordered the columns)?
3.18. I want to change the Header renderer of my
JTable (to change the text alignment, for example), and I can't find a
way to do it! JTableHeader had two new methods added in JDK 1.3, getDefaultRenderer() and setDefaultRenderer(TableCellRenderer) - Philip Milne 3.19. How can I programmatically stop editing in a JTable? This method will do the job: public boolean stopCellEditing() {
try {
int column = table.getEditingColumn();
if (column > -1) {
TableCellEditor cellEditor = table.getColumnModel().getColumn(column).getCellEditor();
if (cellEditor == null) {
cellEditor = table.getDefaultEditor(table.getColumnClass(column));
}
if (cellEditor != null) {
cellEditor.stopCellEditing();
}
}
}
catch (Exception e) {
return false;
}
return true;
}
4. Text4.1. How do I create a JTextField that only accepts numbers, phone numbers, etc.?Create a subclass of PlainDocument and override its insertString() and remove() methods. Inside the overridden method, only use the superclass' method to insert (or remove) the characters if they fit the criteria you are using. 4.2. How do I use the EditorKit for HTML?
4.3. How can I use the HTMLEditorKit
without using a JEditorPane? 4.4. Which version of HTML does the
HTMLEditorKit support? 4.5. How do I use the RTFEditorKit? 4.6. How can I use the RTFEditorKit
without creating a JEditorPane? 5. Trees5.1. How do I put my information into a tree?Use a DefaultMutableTreeNode. Use setUserObject() to include your information in the node. Make sure yourObject.toString() displays the information for your node (unless you are willing to implement a custom TreeCellRenderer). 5.2. How can I get different icons for my tree nodes?
5.3. How do I load nodes on demand? 5.4. Why won't my folder/directory/etc.
TreeNodes draw properly when they don't have any children? 5.5. How do I expand or collapse all tree nodes?
int row = 0;
while (row < tree.getRowCount()) {
tree.expandRow(row);
row++;
}or collapse it like this: int row = tree.getRowCount() - 1;
while (row >= 0) {
tree.collapseRow(row);
row--;
}5.6 How can I automatically
start editing a TreeNode, for example a new node that the user has
added?
It's easy with DefaultMutableTreeNodes and a DefaultTreeModel model: DefaultMutableTreeNode newNode = ... model.insertNodeInto(parentNode, newNode, 0); // or whatever position TreePath path = new TreePath(newNode.getPath()); tree.expandPath(new TreePath(parent.getPath())); tree.setSelectionPath(path); tree.startEditingAtPath(path); 6. Undo6.1. How do I support undo in my application?Create an instance of UndoManager and have it listen for UndoableEditEvents from the model you want to support undo/redo. Use the information from the UndoManager to update the choices your application presents to the user. When the user chooses to perform an undo or redo, call the appropriate methods on the UndoManager. 6.2. How do I create a custom UndoableEdit?
7. Accessibility7.1. How do I make a Swing component accessible?Conveniently, the Swing components are all accessible since JComponent provides default accessibility support. To make a Swing component fully accessible, set the accessibleName or accessibleDescription. For components that have simple text labels, the accessibleName is by default set to the text on the component. Components such as JMenBar or JTextArea that don't have simple text labels need to have the accessibleName explicitly set. To set the accessibleName or accessibleDescription, get the AccessibleContext for the object and use the methods it provides, as in this code fragment: JTextArea noteArea = new JTextArea();
noteArea.getAccessibleContext().setAccessibleName("Notes");
noteArea.getAccessibleContext().setAccessibleDescription(
"The notes you want to take");7.2. How do I make a non-Swing component accessible?
Make your component implement interface Accessible. The Accessible interface has one method, getAccessibleContext(), that returns an instance of AccessibleContext. This is an abstract class that has six methods you must implement. (Override other methods as necessary.) For example, if your class is a custom scrolling marquee, you would override the getAccessibleText() method to return an instance of AccessibleText. It provides methods so that assistive technologies can retrieve more detailed information about the text, for example the individual words in the text. 8. Pluggable Look-and-Feel8.1. How do I get native look-and-feel (instead of the blue/gray "Metal" style)?The Metal (cross-platform) look-and-feel is the default. To get the native one, add this code early in your main() or init() routine: try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex_ignored) {
// default l&f left in place
}8.2. Can I run Windows or Mac
look-and-feel on other platforms? No, they're only permitted on their own platform. Sun believes there are copyright issues related to these look and feels. There is an alternative MacOS look and feel available from http://www.ing.unitn.it/~luttero/javaonMac/ that supports a more Mac-like single menu bar along the top of the screen. 8.3. How do I create a UI delegate for my custom
component? public class MyComponent extends JComponent {
public void updateUI() {
setUI((MyComponentUI)UIManager.getUI(this));
}
public void setUI(MyComponent newUI) {
super.setUI(newUI);
}
public MyComponentUI getUI() {
return (MyComponentUI)ui;
}
public String getUIClassID() {
return "MyComponentUI";
}
}8.4. How
do I create a new look-and-feel? A session at JavaOne '98 described the process: http://java.sun.com/javaone/javaone98/sessions/T309/steveIndex.html 8.5 What other look and feels are available?
9. Java 2D9.1. Where can I find information about Java 2D?JavaWorld has been running a series of articles by Bill Day in its "Media Programming" column:
10. Drag-and-Drop10.1. Where can I find information about drag-and-drop?John Zukowski has published an online article, "Drag-and-Drop How To" at http://java.miningco.com/library/weekly/aa072398.htm. This article has been updated and is now at http://java.about.com/library/weekly/aa011299.htm. Drag-and-drop was featured as a "Question of the Week" at the JDC: http://developer.javasoft.com/developer/qow/archive/1/index.html. More recent information has appeared at: JavaOne presentation http://industry.java.sun.com/javaone/99/event/0,1768,617,00.html The Java DnD FAQ, http://www.rockhoppertech.com/java-drag-and-drop-faq.html
10.2. Can I use drag-and-drop with a JTree?
John Zukowski published another article where he uses a draggable
JTree: "I used DnD with JTree in Java 2 for myself, so it is usable. But
the JDC says bug 4165577 is still in progress. 11. About this documentThis is an FAQ guide to the Swing component library for Java.Feedback is welcome at swingfaq@drye.com. The authors are:
Acknowledgements: Thanks to Marjan Bace of Manning Publications for his encouragement in developing this document. Some information in this FAQ is from Java Foundation Classes: Swing Reference. This FAQ is irregularly posted to comp.lang.java.gui and the swing mailing list. It is also available at http://www.drye.com/swing/faq.html. [Return to top]
Copyright 1999-2002 Stephen C. Drye, 1998-1999 Stephen C. Drye and William C. Wake. All rights reserved. |
|
Copyright 1994-2009, William C. Wake - William.Wake@acm.org |