Applets, AWT and Swing FAQs

What is z-order?
Z-order controls how components are drawn on top of one another. The 0 layer is the highest layer, or the one drawn last. Layer 1 is next, then 2, and so on.

How can I get Pixel Info (width, height, pixel colors) for a text string?
The width and height are actually very easy. All you need to do is get a FontMetrics object for the font you used to draw the string, and ask it:
FontMetrics fm = getFontMetrics(getFont());
System.out.println(fm.getHeight());
System.out.println(fm.getLeading());
System.out.println(fm.stringWidth("This is a sample string"));
Note that the height is the actual space the font requires, while leading is the space the font requests be used between lines of text on the screen.

Which layouts respect which sizing methods?
The Component class defines several size accessor methods to assist the layout process. Each of these methods returns a Dimension object describing the requested size. These methods are as follows: Layout managers will use these sizing methods when they are figuring out where to place components and what size they should be. Layout managers can respect or ignore as much or as little of this information as they see fit. Each layout manager has its own algorithm and may or may not use this information when deciding component placement.

Layout Manager Respects...
BorderLayout preferred height (NORTH, SOUTH)
preferred width (EAST, WEST)
FlowLayout preferred size
CardLayout none
GridLayout none
GridBagLayout preferred size (for initial component sizes)

How do I create radio buttons in AWT?
AWT uses the Checkbox class for both check boxes and radio buttons.

To create a radio button, you need to create check boxes, and add them to a checkboxgroup.


public class Test
{
  public static void main(String[] args)
  {
    Frame f = new Frame();
    f.setLayout(new GridLayout(0,1));  // one columns and multiple rows
    CheckboxGroup group = new CheckboxGroup();
    f.add(new Checkbox("One", group, true));
    f.add(new Checkbox("Two", group, false));
    f.add(new Checkbox("Three", group, false));
    f.pack();
    f.setVisible(true);
  }
}

What is the difference between AWT and SWT?
SWT (Standard Widget Toolkit) is a completely independent Graphical User Interface (GUI) toolkit from IBM. They created it for their new Eclipse Integrated Development Environment (IDE).

IBM began work on SWT a few years ago, because Swing was still immature and didn't perform well. They decided to create a new toolkit to provide better performance using native widgets.

What is the default layout manager of an applet?
For a java.applet.Applet, the default layout manager is FlowLayout.

For the content pane of a javax.swing.JApplet, the default layout manager is a BorderLayout.

How can I get a reference to the container to which a component has been added?
Use component.getParent() method.

How do we stop the AWT Thread? Our Swing application will not terminate.
You need to explicitly call System.exit(exit_value) to exit a Swing application. This is because the event dispatcher thread is not a Daemon thread, and won't allow the JVM to shut down when other threads are dead.

How can I determine the active JFrame?
Call Frame.getFrames() which will return all frames created by the application.
Frame[] f = Frame.getFrames();
Frame active = null;
for (int i = 0; i < f.lenght; i++) {
  if (f[i].isActive()) {
    active = f[i];
    break;
  }
}
How do I change the current look and feel of my Swing program?
You can either call the setLookAndFeel() method of the UIManager class or set the swing.defaultlaf property of your Java program before it starts.

If you wish to change the look and feel of a running program, you will need to call the updateComponentTreeUI() method of the SwingUtilities class to update each top-level window.

Is it possible to know which button user pressed in mouse events?
Use the following code to know which button is pressed.

  public void mousePressed( java.awt.event.MouseEvent evt)
  {
        if (  evt.getModifiers() == InputEvent.BUTTON1_MASK)
             // left button process
        else
            // right button process
  }

How do I ensure a specific row is visible in my JTable?
To ensure a specific row (or cell) is visible, you need to get the rectangle surrounding a specific row/column (cell) than make sure that is visible:

Rectangle rect = table.getCellRect(row, column, true);
table.scrollRectToVisible(rect);

What exactly is the "Event Dispatch" thread (aka "AWT" Thread)?
When you run a GUI applet or application, the code in your main() method creates a GUI and sets up event handling. When you call setVisible(true) for your Frame, Window, Dialog, or when the browser displays the Applet, the user must be able to interact with the GUI.

The problem is that your main() method may not end at that point. It could be busy doing some other task. If the user had to wait for the main() method to finish before they could interact with the GUI, they could end up quite unhappy.

So the AWT library implements its own thread to watch GUI interaction. This thread is essentially a little loop that checks the system event queue for mouse clicks, key presses and other system-level events. (You can also put your own events in the system queue, but that's another story...).

The AWT thread (aka the "Event Dispatch" thread) grabs a system event off the queue and determines what to do with it. If it looks like a click on top of a component, it calls the mouse click processing handler for that component. That component, in turn, could fire other events. For example, if you click on a JButton, the AWT thread passes the mouse click to the JButton, which interprets it as a "button press", and fires its own actionPerformed event. Anyone listening will have their actionPerformed method called.

The AWT thread also handles repainting of your GUI. Anytime you call repaint(), a "refresh" request is placed in the event queue. Whenever the AWT thread sees a "refresh" request, it calls the appropriate methods to layout the GUI and paint any components that require painting.

Note: The AWT "thread" may in fact be implemented by multiple threads under some runtime environments. These threads coordinate effort to watch for mouse clicks, keypresses, repaint requests, etc. As far as you're concerned you can treat this all as one "AWT thread".

How can I validate data entered in a TextField?
You can validate the data in any of the three location

How do I display a multi-line tooltip?
You can include HTML content in tooltip text as follows:
setToolTipText("<html>This is the first line<br>This is the second line</html>");

How do I let my Swing text component support undo/redo?
The Swing text components come with built in support for undoing and redoing text operations. All you have to do is associate an UndoManager to the Document of the text component:

JTextField textField = new JTextField();
UndoManager manager = new UndoManager();
Document document = textField.getDocument();
document.addUndoableEditListener(manager);

Then, when it comes time to undo or redo the last edit, you would notify the UndoManager by calling either the undo() or redo() method of the manager. If the manager cannot undo an operation, the runtime exception CannotUndoException is thrown. If a redo operation cannot be redone, the runtime exception CannotRedoException is thrown.