AWT Interview Questions
By Ramakrishna on Jun 17, 2008 in AWT Question
Q) Why do I get this when using JDK 1.1 under X Windows? java.lang.NullPointerException at sun.awt.motif.MFramePeer.<init>(MFramePeer.java:59) at sun.awt.motif.MToolkit.createFrame(MToolkit.java:153) at java.awt.Frame.addNotify(Frame.java) at java.awt.Window.pack(Window.java)
A. There’s a missing font on your system. Move font.properties from the “lib” subdirectory aside to font.properties.bak Then it won’t look for the font and fail to find it.
The problem occurs because the Motif AWT libraries use the Font “plain Dialog 12 point” as a fall-back default font. Unfortunately, when using a remote X server sometimes this font isn’t available. On an X-terminal, the diagnostic may be slightly different, a segv % appletviewer HelloWorldApplet.html SIGSEGV 11*segmentation violation si_signo [11]: SIGSEGV 11* segmentation violation si_errno [0]: Error 0 si_code [1]: SEGV_ACCERR [addr: 0x14]
To determine which fonts you have, issue a command such as xlsfonts > ~/fonts.txt
Then pick through the long list of fonts to determine which ones you want to use. The xfd program will let you look at a font: xfd -fn “your font name here” &
Q) Why is GridBagLayout so hard to use?
A. GridBagLayout was contributed to Javasoft by a programmer who wanted to support the Java effort. It was intended as a proof that the AWT offered enough features for programmers to write their own layout managers. It wasn’t designed with human factors and ease of use in mind. If it bothers you (it bothers me) then just don’t use it. Create your GUI on several panels and use the other layout managers as appropriate to get the exact effect you want. The official story from the project leader of the AWT project, as explained to the Mountain View Java Users’ Group on Dec 4 1996, is: “The case has been made and is now accepted that GridBagLayout is too hard to use for what it offers. GBL will continue to be supported, and something better and simpler will eventually be provided as well. This “better GBL” can be used instead of GBL.”
Bottom line: nobody has to waste any effort on GBL, there are better alternatives available now, and it will be replaced by the SwingSet “SpringLayout” Springs & Struts style layout manager to be introduced as part of the Java Foundation Classes with JDK 1.2.
Q) How do you change the font type and size of text in a TextArea?
A. myTextArea.setFont(new Font(“NAME”, <STYLE>, <SIZE>)); where NAME is the name of the font (eg Dialog or TimesRoman). <STYLE> is Font.PLAIN, Font.ITALIC, Font.BOLD or any additive combination (e.g. Font.ITALIC+Font.BOLD). <SIZE> is the size of the font, e.g. 12.
e.g. new Font(“TimesRoman”, Font.PLAIN, 18);
Q) MyClass works fine except when I try to set a particular font. I just can’t seem to get it to work in Win95, but I can get it to work on a MacOS and Unix.
A. You probably specified a font name that isn’t available under your Win95; this is one of those cross-platform differences that can bite you if you over-specify for one platform, like specifying “Ariel” as a font and expecting it to work on something other than Windows. On both Windows 95 and Solaris 2.6, these fonts Dialog SansSerif Serif Monospaced Helvetica TimesRoman Courier DialogInput ZapfDingbats are revealed by this code:
import java.awt.*;
class foonly
{
static public void main(String s[])
{
String n[] = new Frame().getToolkit().getFontList();
for (int i=0; i<n.length; i++)
System.out.println(n[i]);
System.exit(0);
}
}
In other words, You can get a String array of the names of the fonts by String[] fonts = Toolkit.getDefaultToolkit().getFontList()
Q) Is it possible to draw a polygon or a line more than 1 pixel wide?
A. JDK 1.1.1 doesn’t have support for this. The standard workaround for drawing a thick line is to draw a filled polygon. The standard workaround for drawing a thick polygon is to draw several polygons. There is a useful class at http://www.apl.jhu.edu/~hall/java/GraphicsUtil.html
It extends the drawxxx and fillxxx methods of java.awt.Graphics. It adds a Line Width argument to most of the drawxxx methods, a Color argument to most of the drawxxx and fillxxx methods, and a Font argument to draw String and drawChars.
Q) I use add(Component) to add Components to the Container. Is there any way to explicitly set the z-order of these Components?
A. JDK 1.0 has no way to explicitly set the z-order of components. You can try it heuristically, based on the browser you’re using, or you can use CardLayoutManager to ensure the panel you want is at the front.
IN JDK 1.1 the z-order of components can be controlled by using the the method add(Component comp, int index). By default, components are added 0 to N. The method paint of class Container paints its visible components from N to 0.
Q) When I call repaint() repeatedly, half my requests get lost and don’t appear on the screen. Why is this?
A. repaint() just tells the AWT that you’d like a paint to happen. AWT will fold several adjacent repaint requests into one, so that only the most current paint is done. One possible workaround might be to use a clip rectangle and only paint the different areas that have changed.
Q) What is the difference between Component’s setForeground(Color c) and Graphics’s setColor(Color c) ?
A. First of all, these methods do the same thing: set the foreground color to the value of the parameter. The difference lies in where you use them. There is also a Component.setBackground that will set the background color.
If you are in a constructor or an event handler (e.g. “click here to turn the canvas blue”) you have a Component and should use the setForeground() method. If you are in a paint() method, that takes a Graphics context as its argument so you will typically use g.setColor(c).
Unlike a Component, a Graphics object doesn’t have a background color and a foreground color that you can change independently. A Graphics object arrives in the color(s) inherited from the drawing surface. From then on, any rendering (drawLine(), drawRect(), fillOval(), etc.) will be done in the setColor() color. Because they do different things, the Component and Graphics methods have different names.
Q) When I start a mouse drag inside a Component, and go outside the Component, still dragging, the mouse events still get sent to the Component, even though I am outside it. Is this a bug?
A. No, it is the specified behavior. The java API documentation says: “… Mouse drag events continue to get sent to this component even when the mouse has left the bounds of the component. The drag events continue until a mouse up event occurs. …”
It is done for the convenience and ease of the application programmer. It allows you to handle all drags from the place of origin. If you don’t want this, simply look at the coordinates of the mouseDrag Event, and if they are outside the Component, ignore them.
Q) What’s all this about subclassing Canvas and overriding paint() ? Can’t I just do a getGraphics() for a component, and draw directly on that?
A. You can do that, and it might work up to a point (or it might not). A problem arises when the window system wants to refresh that component
e.g. because it has been partially obscured and is now revealed. It calls paint(), and that has no knowledge of the other g.drawing() you have done.
Q) But couldn’t the AWT just remember what has been drawn to a Graphics context, and replicate that instead of calling paint()?
A. It could, but that is not how it works. In practice it is a lot simpler to be able to look at the paint method, and see explicitly all the things that will be done to draw that component. Bottom line: use paint(), not g=getGraphics(); g.drawString( …
Q) How can I get the dimensions and resolution of the screen?
A. java.awt.Toolkit.getDefaultToolkit().getScreenSize() java.awt.Toolkit.getDefaultToolkit().getScreenResolution() Screen resolution is in dots-per-inch.
Take a look in the Toolkit class for other useful methods.
Toolkit.getDefaultToolkit().getColorModel().getPixelSize() gets you the color model in terms of bits per pixel.
Math.pow(2,Toolkit.getDefaultToolkit().getColorModel().getPixelSize()) gets you the color model in terms of number of colors. Or use this: 1 << Toolkit.getDefaultToolkit().getColorModel().getPixelSize()
That does a shift left to calculate the power of two.
Q) How do I allow for the size of the title bar and border when I draw a Frame?
A. Use MyFrame.getInsets(). This returns a java.awt.Insets object which has four ints: top, left, bottom, right, giving the number of pixels each of those margins are inset from the top. You can use these value to adjust the Dimension object returned by component.getSize().
Q) When I run the Swing demo on Win95 I get an error “Out of environment space”
A. That’s because you don’t have enough space for your DOS environment. You can fix this with: Right click your MS-DOS Prompt icon or window and choose Properties. Choose “Memory” and on “Initial Environment” choose 4096 instead of “auto”. Run Swing again, you’ll be OK.
Q) How do I resize a List? I had a List defined as List tlist = new List(10); but the Strings in the list were 80 characters long and only the first 15 were being shown. I was not able to resize the List to display the contents without using the scroll bar.
A. A List cannot be resized in a constructor, so add the following to the Applet (or wherever) public void paint (Graphics g) { tlist.setSize(200,200); } Then before showing panel/frame with the List: tlist.resize(400,400);
Q) How can my program tell when a window is resized?
A. Override the setBounds() method of Component to do what you want. Of course, have it call super.setBounds() as well. Note that setBounds() replaces reshape() which is deprecated.
Note the new APIs call the deprecated APIs instead of the other way round. For example, Component.setBounds calls Component.reshape, instead of reshape calling setBounds.
Q) How do I get back to a normal echo after I have used TextField.setEchoChar(‘*’);
A. TextField.setEchoChar(‘\0′) works on most Windows based browsers… but for most other platforms (ie: Netscape under UNIX), it just locks up the textfield.
There is only one good solution, and that is to make two TextFields on top of each other, one normal, and one with .setEchoChar(‘*’), and switch between them.
Q) How do I clear the contents of a TextArea?
A. Set it to a null String with this: area.setText(“”);
Q) What are those preferredSize() and minimumSize() methods in Component?
A. Those methods allow a LayoutManager to calculate the preferred and minimum sizes of the Components it is arranging. You can control the values that the LayoutManager gets by creating subclasses of the Components you are using and overriding these methods.
Q) How can I force a synchronization of the graphics state, e.g. of a cursor change, or an animation frame to be rendered?
A. This is done by the sync() method in the toolkit. So just use: AnyComponent.getToolkit().sync();
Q) How do I plot a single pixel to the screen?
A. Use g.drawLine(x1,y1,x1,y1) to draw a line one pixel in length.
Q) How can I tab between components?
A. In JDK 1.0, you have to read the key press, and program it explicitly. JDK 1.1 supports tab and shift-tab (previous field) automatically. The tab order is the order that the components were added to the container.
