Java Graphics, AWT, Swing Interview Questions-

Q: How can I minimise "Flicker" in animation? Solution 1:
Answer: Solution 1:
Override update() : Flickering in animation occurs because default update() method clears the
screen of any existing contents and then calls paint(). To reduce flickering, therefore, override
update(). Here is how just add the following code to your applet:
public void update(Graphics g) {
paint(g);
}
What the update is now doing is just calling paint() and not clearing it, a further refinement to
the above will be to override update() method and painting only the region where the changes
are taking place. Here is how:
public void update(Graphics g) {
g.clipRect(x, y, w, h);
paint(g);
}
Solution 2 will be described tomorrow
Q: How can I minimise "Flicker" in animation? Solution 2:
file:///C|/330_new/330_new/graphics-I.htm (1 of 6) [2003-07-22 22:07:50]
Graphics, AWT, Swing I part
Solution 1 was described in our tip yesterday
Solution 2:
Use double-buffering : double buffering is the process of doing all your drawing to an offscreen
and then displaying the entire screen at once. It is called double buffering because there are
two drawing buffers and you switch between them. Use double buffering only if the above
solution alone does not work. The following code snippet describes how to do it.
Image offscreenImage;
Graphics offscreenGraphics;
offscreenImage = createImage(size().width, size().height);
offscreenGraphics = offscreenImage.getGraphics();
offscreenGraphics.drawImage(img, 10, 10, this);
g.drawImage(offscreenImage, 0, 0, this);
Q: The following app works fine, but when I start it, I cannot close it using the X at the right
top of the form...
Please help me on the following. I'm just starting to use java (JDK1.3). The
following app works fine, but when I start it, I cannot close it using the X
at the right top of the form. What should I add to fix this problem? The
source is shown below.
import java.awt.*;
import java.awt.event.*;
public class MyApplication extends Frame{
public static void main(String args[]){
Frame f = new Frame("MyApp");
f.setLayout(new FlowLayout());
f.add(new Button("A"));
f.setVisible(true);
}
}
Answer: You should add a listener to handle the closing of the window when the X
box gets clicked on.
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent evt){
System.exit(0);
}
});
Read on this, and other ways to do it, in the sections dealing with
event handling, in whichever Java text you are using.
Q: How can I set a JFrame to be full screen at the start of a program? I want no borders, no
file:///C|/330_new/330_new/graphics-I.htm (2 of 6) [2003-07-22 22:07:50]
Graphics, AWT, Swing I part
titles and I just want to use the entire screen.
Answer: Try using JWindow instead, that one can be customized to have no borders or titles...
as for size, I think you can use
setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration().getBounds());
to fill out the entire screen.

Q: Why can not I mix AWT and Swing?
Recently, I have been hearing a lot of people from various newsgroups and website saying,
java swing and awt can't be in the same application. They will not work together and they might
produce unexpected results. At the same time, i don't hear people saying "why" you shouldn't
use swing and awt together. Could someone out there shed some light for me. Is their any
logical reason why we shouldn't mix swing and awt in the same application/applet. If there is a
problem mixing swing and awt... what are the results, what can happen? I design using IBM's
Visual Age for Java 3.0, and I mix swing and awt in the same application/applet, it works fine
when testing in the IDE (I haven't tested it outside of the IDE yet). If you have tested
application/applets outside of the IDE, please let me know what happened?
Answer: There are findamental incompatibilities in the way they draw themselves.
AWT java classes are not "pure" Java classes, they use underlaying C/C++ native code
(dependable on operation system) that can cause different appearence in different OSs.
Swing is pure Java implementation and has no native code at all. Swing applications look the
same.
> If there is a problem mixing swing and awt... what are the results,
> what can happen?
Some objects drawn on top of others are not properly occluded. This is most obvious with drop
down menus, which have a tendency to stay visible even after you have selected a menu item.
Another problem is that if you use AWT components on a JTabbedPane they will not disappear
when you switch tabs. There are many similar issues.
Q: Again about difference between AWT and Swing
I have a question: What are the architectural differences between Swing and AWT??
Answer: by Odd Vinje
There are no big architectural differences, the class hierarchy is almost the same. The reason
is that Swing is built upon AWT.
The most significant difference is how the components are drawn to the screen. AWT is so
called heavyweight components and have their own viewport which sends the output to the
screen. Swing is ligthweight components and does not write itself to the screen, but redirect it
to the component it builds on. Heavyweight components also have their own z-ordering. This is
the reason why you can't combine AWT and Swing in the same container. If you do, AWT will
file:///C|/330_new/330_new/graphics-I.htm (3 of 6) [2003-07-22 22:07:50]

Graphics, AWT, Swing I part
always be drawn on top of the Swing components.
You can combine AWT and Swing, just don't do it in the same container (e.g. panel, groupbox,
etc.) and don't put a heavyweight component inside a lightweight.
Another difference is that Swing is pure Java, and therefore platform independent. Swing looks
identically on all platforms, while AWT looks different on different platforms.
Q: I have a JFrame for customer registration with a lot of input fields. In this screen you can
create a new customer, get customer with specified customer number and you can update a
customer.
In this JFrame is it possible to clear all fields without specifying each field?
Answer: This snippet is for TextFields, you should be able to adapt for JtextFields very easily.
public static void resetTextFields(Container c) {
Component [] components = c.getComponents();
for (int i = 0; i < components.length; i++ ) {
if (components[i] instanceof Container)
resetTextFields((Container) components[i]) ;
else if (components[i] instanceof TextField)
((TextField) components[i]).setText("") ;
}
}
Bye.
---
Real Gagnon from Quebec, Canada
* Looking for Java or PB snippets ? Visit Real's How-to
* http://www.rgagnon.com/howto.html
Q: Swing is "lightweight" components. Its graphics primitives are implemented in 100%
Pure Java. How does it draw pixels on screen?
Does it still rely on any native code to access the frame buffer?
Answer: We mentioned before in our tips that Swing components is 100% pure Java.
It isn't fully correctly if we are speaking about containers on which they can draw. Swing is still
based on AWT, and even Swing components must have at least one heavyweight container. In
other words, JFrame, JApplet are *not* lightweight.
Q: How can I change the default icon on application window (java cup) to my own?
Answer:
window.setIconImage(Toolkit.getDefaultToolkit().getImage("image.gif"));
file:///C|/330_new/330_new/graphics-I.htm (4 of 6) [2003-07-22 22:07:50]
Graphics, AWT, Swing I part
Q: Need I to remove all the listeners on all of the components in the Frame when I close
window of the Frame?
I've got a Frame, which has in it a bunch of components, some of which themselves may be
containers. Many of the components in this frame have listeners.
When somebody closes the window of the Frame, I want to completely get rid of the Frame, so
that the garbage collector will later clean it up, freeing it's memory. However, I haven't yet
figured out a way to do this without tracking every single component by myself. Just calling
dispose() on the main Frame doesn't seem to be good enough. Calling "RemoveAll()", even
recursively, doesn't seem to be good enough.
I *suspect* that the problem may be that I have to remove all the listeners on all of the
components in the Frame. Is there a way to get a list of the listeners out of a given component?
I really don't want to have to track every single button I add to every single Frame, and every
single Listener I add to every single component. If I have to keep track of all of that, it sort of
defeats a lot of the advantages of a well-defined object oriented system.
Answer: I think you're slightly confused here. When another object registers as a listener for a
component within the frame, it's the component within the frame that is holding a reference to
the external object in its listeners list - not vice versa.
Which means you don't really need to explicitly remove every listener that any other object
registered on components in the f rame.
What you need to worry about is however the listeners that the frame itself registered with
some other components that are still alive. If the frame gets disposed without removing these,
the objects that were being listened to will retain a reference to the frame and this can cause
the frame to stay around as long as these objects which hold these references stay alive.
So look for all Listeners that your frame registered itself as on components external to itself
(should be fairly easy to see since you normally do it in your constructor) and remove those
before disposing off the frame.
--
Kala
Q: Main disadvantage of Java GUI is that it is often slow. But I have seen also very fast
working GUIs. Unfortunately the code is hidden and I do not know the technique for writing of
fast Java GUIs.
Answer: I can describe one of main technique you can use. It does not give you full solution,
but will certainly speed up your GUI.
The main idea is to use "lazy" initialization. Instead of creating and initializing of all GUI
components in constructors during start up time postpone it to later time until you really need.
Let say, you have a lot of tab panels with many elements on each tab panel.
Your constructors should be "quite" empty and do not create and initialize those small elements
until your tab panel is chosen. You should have very small constructor for tab panel itself and
file:///C|/330_new/330_new/graphics-I.htm (5 of 6) [2003-07-22 22:07:50]
Graphics, AWT, Swing I part
additional lazy constructor for the rest. It should be called when user clicks on that particular
tab.
This does not decrease the full time of initialization, but spreads it up. The user will not feel big
delays during start up of your application. You should use these lazy constructors just before
you are going to call any paint method.
--
AP. (J.S.)
(c)1999, 2000, 2001, 2002 JavaFAQ.nu. All rights reserved worldwide.
This document can not be changed, either in whole or in part
without the express written permission of the publisher.
All questions please
file:///C|/330_new/330_new/graphics-I.htm (6 of 6) [2003-07-22 22:07:50]
Graphics, AWT, Swing II part
Receive our newsletter with new tips! More than 13,500 subscribers (by July
2003) can not be wrong! They read our tips every week!
To subscribe to "The Java FAQ Daily Tips" weekly edition newsletter send email
with "subscribe" word in the header and the body (write just subscribe
without ""!!!) to:
javafaqtips-request@javafaq.nu
or on the web:
http://www.javafaq.nu/plm2html/my_subscription.shtml
Graphics, AWT, Swing - II

Q: I’ve a question where skillful java programmers sure will laugh about, but I ask
nevertheless.
What exactly means >>> Graphics g <<<? How must I use it and why is it so important to use?
Answer: It basically says: "where should I paint? On the screen, on some RAM, on a printer
buffer?"
It is sort of a conduit to that medium.
Graphics class is the set of tools, which allows you to set background, colours, fonts; draw
lines, circles, arcs, polygons etc to a component. Here is the definition from the class javadoc
documentation:
"The Graphics class is the abstract base class for all graphics contexts that allow an application
to draw onto components that are realized on various devices, as well as onto off-screen
images.
A Graphics object encapsulates state information needed for the basic rendering operations
that Java supports.
This state information includes the following properties:
The Component object on which to draw.
A translation origin for rendering and clipping coordinates.
The current clip.
The current color.
The current font.
The current logical pixel operation function (XOR or Paint).
file:///C|/330_new/330_new/graphics-II.htm (1 of 6) [2003-07-22 22:07:51]
Graphics, AWT, Swing II part
The current XOR alternation color (see setXORMode(java.awt.Color)). "
--R. Green, Gilgames
Q: How can i disable the right click on the label?
I have a JTree and a JPopup: i've forced the code to be able to select the node with a right click
and show the popup. The problem is that i can right click on the popup labels to select them,
but i'd like to select them only with a left click. How can i disable the right click on the label?
Can somebody help me please?
Answer: You can add in an if loop that only executes if the left mouse button is down using
code like the following:
MouseEvent e;
if ((e.getModifiers() & e.BUTTON1_MASK) != 0)
{ // code for left button click }
and just so you know,
InputEvent.BUTTON2_MASK is the middle or scroller button
InputEvent.BUTTON3_MASK is the right button in windows
--
by MSW
Q: Is it possible to change delays that affect appearing, keeping and disappearing of
tooltip?
Answer: It was difficult to find the answer but finally I found in "Swing" book that is free to you
on our site.
The ToolTipManager is a service class that maintains a shared instance registered with
AppContext. We can access
the ToolTipManager directly by calling its static sharedInstance() method:
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
Internally this class uses three non-repeating Timers with delay times defaulting to 750, 500,
and 4000. ToolTipManager uses these Timer’s in coordination with mouse listeners to
determine if and when to display a JToolTip with a component’s specified tooltip text. When the
mouse enters a components bounds ToolTipManager
will detect this and wait 750ms until displaying a JToolTip for that component. This is referred
to as the initial delay time.
A JToolTip will stay visible for 4000ms or until we move the mouse outside of that component’s
bounds, whichever comes first. This is referred to as the dismiss delay time. The 500ms Timer
represents the reshow delay time which specifies how soon the JToolTip we have just seen will
appear again when this component is re-entered.
Each of these delay times can be set using ToolTipManager’s setDismissDelay(),
setInitialDelay(), and setReshowDelay() methods.
ToolTipManager is a very nice service to have implemented for us, but it does have significant
file:///C|/330_new/330_new/graphics-II.htm (2 of 6) [2003-07-22 22:07:51]
Graphics, AWT, Swing II part
limitations. When we construct our polygonal buttons we will find that it is not robust enough to
support non-rectangular components.
Q: I know how to make a text box using Visual Basic that can only accept certain keys for
example if I wanted to make a box where you can type only numbers in it or letters. However,
when it comes to Java I have not been able to figure this out. Is there a way to do this and
make a textbox where you can only type letters in it?
Answer: First of all, 'ASCII' is not a synonym for 'text'. ASCII is just one of many ways of
encoding text to numeric values. It is 7-bit and only includes values from 0 through 127.
Now, on to your question. With ASCII, 'numbers' and 'letters' are a little easier to check, since
the only letters are 'A'-'Z' and 'a'-'z'. However, Java uses Unicode and has all sorts of fun extra
characters.
But you do have a few handy methods on the java.lang.Character class such as isDigit and
isLetter
Now, if you are using swing, then to achieve what I'm guessing you want is quite simple. Just
hook a custom text document to the JTextField you're using and have it do the filtering.
** Here's the part of The Java Tutorial that goes over it
http://java.sun.com/docs/books/tutorial/uiswing/components/textfield.html#validation
Here's someone's Swing FAQ on that
http://users.vnet.net/wwake/swing/faq.html#text_check
Here's a JavaWorld article that describes how to do that to limit the length of input. Shouldn't be
too hard for you to change to your specific needs.
http://www.javaworld.com/javaworld/javaqa/2000-05/02-qa-0512-textbox_p.html
All these links were from the first page of a search on http://www.google.com
Google is your friend!
--
John A.Cruz
Q: I'm trying to do some image manipulation (mainly resizing images) in a Linux Servlet/JSP
environment, to do that I use the Java 2D API.
This works fine on my Windows development PC, but does not work on an X-less Linux hosting
platform. My hosting company is not running X and has no plans to do so.
So my question is, it is possible to use the Java 2D API on a Linux box without an X server
running?
Answer Part 1: A frequently asked question in the context of loading images is that of the
missing X server. Unix users who just want to load an image via the AWT without displaying it
get an error message if there is no X server installed. In fact, the X server is required for that.
file:///C|/330_new/330_new/graphics-II.htm (3 of 6) [2003-07-22 22:07:51]
Graphics, AWT, Swing II part
java.awt.Graphics methods such as drawLine (), fillOval (), drawString (),... are implemented in
the default JVM with native graphical functions (except in some cases for Java2D) : That
means that drawLine () finally calls a GDI system function on Windows or X11 function on a
X11/UNIX machine even if the drawing is done in an off-screen image using the class
java.awt.Image. This ensures the best performance for drawing graphics with Java.
When no X11 Display is available on UNIX machines or when GDI resources are low on
Windows, it is impossible to compute off-screen images with java.awt.Graphics methods, even
if your program doesn't need to display these images. Typically, this situation happens for
servlets returning dynamically generated images like pies, charts or web counters.
It is also impossible to compute off-screen images when the Java security manager forbids
access to any Toolkit or the AWT library.
Possible solutions will be published tomorrow! (end of Part 1)
Part 2 (Part 1 in yesterday's tip):
Possible solutions:
1. Install a virtual framebuffer X Windows System server for XFree86. Xvfb (X Virtual Frame
Buffer) is an X server that is able to run on machines with no display hardware and no physical
input devices.
Xvfb emulates a dumb framebuffer using virtual memory. Xvfb doesn't open any devices, but
behaves otherwise as an X display. Xvfb is normally used for testing servers. Using Xvfb, the
mfb or cfb code for any depth can be exercised without using real hardware that supports the
desired depths. Xvfb has also been used to test X clients against unusual depths and screen
configurations, to do batch processing with Xvfb as a background rendering engine, to do load
testing, to help with porting an X server to a new platform, and to provide an unobtrusive way of
running applications which really don't need an X server but insist on having one.
2. Use PJA Toolkit available for free at:
http://www.eteks.com/pja/en/
3. Use Java 1.4. beta which available now. This version can work without X-server
Q: I'm currently developing my first actual graphical application in Java, using Swing. I feel
that I've got a pretty good grip at object-oriented design and analysis, but I'm somewhat
uncertain when it comes to connecting the user interface with the application logic.
Should the GUI components be in the main application class, separated into several classes
depending on their position on the screen, or included in the "application logic"-classes? What
about the different EventListener I need?
Answer: The biggest, biggest mistake people frequently make is to embed application logic
right in with their GUI code. It is almost inevitable with most programmers, unfortunately.
file:///C|/330_new/330_new/graphics-II.htm (4 of 6) [2003-07-22 22:07:51]
Graphics, AWT, Swing II part
One idea is to use top-level packages, perhaps GUI, kernel, and database.
In the GUI package, have one package for each frame or main thing, like gui/main, gui/login,
gui/help, gui/detail, etc.
From all the many tiny pieces of gui code that see button pushes, get events, enable or disable
things based on user authorization level, etc, do *NOT* embed application logic there.
Make all these tiny pieces of gui code call a separate NON-GUI arbiter interface (not class) that
has methods like:
* void initialize ()
* void beginSearch (String phoneNumber)
* void login (String user, String password)
* void help (String subject)
* void exitApplication ()
The GUI calls an interface (the arbiter), and the arbiter calls a simple interface to the GUI. This
is one scheme that separates the GUI from application logic.
--
Max Polk
Q: I would like to display images of various sizes using JInternalFrame.
1. I want to create a JPanel and paint the image on this JPanel.
2. Create a JScrollPane and add the JPanel to the JScrollPane.
3. Add the JScrollPane into the JInternalFrame.
4. I want to set the size of JInternalFrame to fit the image size.
I am having trouble with the setSize() method of JInternalFrame.
If I don't use this method, the JInternalFrame doesn't appear.
But I cannot seem to find a good way to set its size to match
the image size.
Answer: Basically you have three ways to set the size of JInternalFrame:
You can use either: setSize, pack, or setBounds. When you call pack() instead of setSize, the
JInternalFrame calculate the size based on it's content inside.
One way would be to use ImageIcons wrapped into JLabels, add them to your component and
call pack() on the JInternalFrame instead of a fixed size.
As an alternative way instead of overriding the paintComponent() of your JPanel, what you
could do as well, of course and decide whether you like to draw the image on it's original size,
scaled or tiled. But you will then need to determine in turn the size of your JPanel, IMO. Thus, I
think, it might be the better approach to use ImageIcons instead.
--
Linda
Q: I need some picture icons for my application that I'm building. Could someone point me
to some place where I could get some pictures?
file:///C|/330_new/330_new/graphics-II.htm (5 of 6) [2003-07-22 22:07:51]
Graphics, AWT, Swing II part
Answer: We have the copy of Java TM Look and Feel Graphics Repository on our site here:
http://javafaq.nu/java/graphics/java-look-and-feel.shtml