comp.lang.java.gui FAQ

  • Thread starter Thomas Weidenfeller
  • Start date
T

Thomas Weidenfeller

Archive-name: computer-lang/java/gui/faq
Version: $Revision: 1.19 $
Posting-Frequency: monthly
Copyright: Copyright (c) 2003 - 2006 Thomas Weidenfeller
Maintainer: Thomas Weidenfeller. See below for mailing instructions.
Last-modified: $Date: 2006/01/27 09:55:05 $

comp.lang.java.gui FAQ
________________________________________________________________________

Table of Contents

PART I =================================================================

SECTION 1 - Introduction
Q1.1 What is this, and what does it contain?
Q1.2 What's not in here?
Q1.3 Where do I find a copy of the FAQ?
Q1.4 There are so many Java FAQs.
Which is the right, official one?
Q1.5 Does Sun support or endorse this FAQ?
Q1.6 I noticed broken links in the FAQ.
Don't you verify them before publishing?
Q1.7 Is there an HTML, Word, <whatever format> version of the FAQ?
Q1.8 What is AWT?
Q1.9 What is Swing?
Q1.10 What is SWT?

SECTION 2 - The comp.lang.java.gui Newsgroup
Q2.1 What is the newsgroup's charter? What are acceptable topics?
Q2.2 Which topics are not welcome in the newsgroup?
Q2.3 Where can I find an archive of the newsgroup?
Q2.4 What is an SSCCE?
Q2.5 Why don't people like top-posting? What is top-posting?
Q2.6 Is there more about posting to newsgroups and asking questions?
Q2.7 Does Sun support or endorse the newsgroup?

SECTION 3 - The Top 5 Questions
Q3.1 My GUI freezes or doesn't update. What to do?
Q3.2 How do I update the GUI from another thread?
Q3.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?
Q3.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?
Q3.5 How to create a transparent or non-rectangular window?

SECTION 4 - Architecture
Q4.1 What is this Model-View-Controller (MVC) stuff?
Q4.2 What is the Swing single-threading issue?
Q4.3 What is the right way to start a Swing GUI?
Q4.4 What is full-screen exclusive mode?
Q4.5 What is active rendering?

PART II ================================================================

SECTION 5 - Window / [J]Frame / [J]Dialog (Top-Level Containers)
Q5.1 How can I ensure a window is always on top of all other windows
using AWT or Swing?
Q5.2 How can I (de)iconify a window?
Q5.3 How can I replace/remove the icon in the title bar (window
decoration) of a [J]Frame?
Q5.4 How to replace the icon in the title bar (window decoration)
of a [J]Dialog?
Q5.5 My modal dialog goes behind the main window. How can I ensure
it is in front instead?
Q5.6 How to bind the escape key to the JDialog cancel operation?
Q5.7 How can I implement my own JFrame/JDialog close handling?
Q5.8 How Do I center a window on the screen? How do I get the
screen size?
Q5.9 How to ensure a minimum or maximum window size?
Q5.10 How to ensure a particular aspect ration of a window?
Q5.11 How can I delegate the window placement to the window system
or manager?
Q5.12 I need to take some toolbar (dock, panel) size into account when
calculating a window position an/or size. How?
Q5.13 My window layout is displayed incorrectly. I have to move
the window, before the layout is right. What's wrong?
Q5.14 How can I display a Splash Screen at the start of my Program?

SECTION 6 - [J]Component (Widgets)
6.1 General Questions
Q6.1.1 How do I position components (widgets) on a window?
Q6.1.2 How to create a transparent widget?
Q6.1.3 How to create a non-rectangular widget?
Q6.1.4 What are Insets?
Q6.1.5 How do I find a component's top-level container (e.g.
the window)?

6.2 JTree
Q6.2.1 I changed the data / structure for my JTree, but the display
doesn't get updated. What's going on?
Q6.2.2 How do I set a custom icon for a node?
Q6.2.3 How do I remove all my nodes from a JTree at once?

6.3 Styled Text / JEditorPane / JTextPane
Q6.3.1 Can I use RTFEditorKit to read RTF documents created by Word?
Q6.3.2 I have problems using the Swing HTML parser to parse all
kinds of HTML. Is this normal?
Q6.3.3 Some of my CSS styles don't work out. Is this normal?
Q6.3.4 Can I use Swing's HTML support to write a web browser?
Q6.3.5 Can I use Swing's HTML support to build an on-line
help system or e-book?
Q6.3.6 If HTML support is really so broken in Java, what is it
good for?

6.4 [J]TextArea
Q6.4.1 I append text to a JTextArea. How to ensure the text
area is always scrolled down to the end of the text?
Q6.4.2 How to use several different fonts (styles, sizes) in
one [J]TextArea?

6.5 [J]Label / [J]Button
Q6.5.1 How can I have multiple Lines in a [J]Label?
Q6.5.2 I want to have a hyperlink in a [J]Label. How can I do this?
Q6.5.3 How do I make a JButton the default button in a JDialog?

SECTION 7 - JScrollPane
Q7.1 I added a component (e.g. a JPanel with an image) to a
scrollpane, but the scrollpane doesn't show it at the right
size / without scrollbars, etc. What's wrong?

PART III ===============================================================

SECTION 8 - Graphics & Painting
Q8.1 What is the equivalent of AWT's Canvas in Swing?
Q8.2 When drawing on a JPanel, the background is garbled.
Q8.3 How do I generate some charts / plots in Java?
Q8.4 How to draw some graphs in Java?
Q8.5 I want to write a diagram editor. Where to start?
Q8.6 How do I draw lines between JLabels on a JPanel?
Q8.7 How to debug graph painting?
Q8.8 I need to draw a tree. How?
Q8.9 I need an algorithm for drawing ...
Q8.10 When I subclass JPanel/JComponent, I need to override paint(),
right?
Q8.11 Why does drawImage() fail when I try to display a loaded image?
Why are the width and height of my loaded image both zero?
Q8.12 How do I resize (zoom in/out) my Graphics?
Q8.13 Where do I find the icons which are used by Swing
itself?
Q8.14 Where do I find typical application icons?

SECTION 9 - Fonts
Q9.1 Which Fonts can I use? Can I use font <xyz>?
Q9.2 How to turn on text antialiasing in Swing?
Q9.3 Why do some of my characters get displayed as squares?

SECTION 10 - Other Common Questions
Q10.1 My GUI has rendering problems when the JMenu opens over my
top Panel ...
Q10.2 Can I use Swing for Applets?
Q10.3 How do I change a color/font/etc. globally for an
application?
Q10.4 How do I get all the UIDefaults, and what do they mean?
Q10.5 Why is Swing so slow?

SECTION 11 - Non-GUI Questions
Q11.1 How do I do a text/console UI in Java?
Q11.2 How can I do this JavaScript thing on my web site?
Q11.3 I want to make ...

SECTION 12 - Resources
12.1 Sun's Java Web Site
12.2 Other Sun Sites
12.3 Icons
12.4 Miscellaneous Examples, Tips and Tricks
12.5 Style Guides
12.6 SDK Documentation
12.7 More Swing
12.8 Online Magazines
12.9 Java 2D API
12.10 Java 3D API
12.11 General Java
12.12 More?
Q12.12.1 But I need more!

SECTION 13 - Improvement Suggestions

SECTION 14 - Acknowledgments
________________________________________________________________________


PART I
========================================================================

SECTION 1 - Introduction
~~~~~~~~~~~~~~~~~~~~~~~~

Q1.1 What is this, and what does it contain?

This is the FAQ for the comp.lang.java.gui newsgroup. It mostly deals
with Java Standard Edition Swing issues, and contains some AWT
information, too.

In many cases these are also topics many readers would like NOT to see
discussed again soon.


Q1.2 What's not in here?

This is not a general introduction to programming, Java programming, or
GUI programming. Further it is assumed that the reader is familiar with
Java and GUI terminology.

Also, the following topics are either not covered at all or just cursory
touched, since they are not often discussed in c.l.j.g, have own groups,
and/or the FAQ author is not knowledgeable about them:

* J2ME GUI programming

* Java 3D programming (see <
* Java game programming

* Computer graphics algorithms
(see <

Q1.3 Where do I find a copy of the FAQ?

1) The FAQ is regularly posted to

<
2) At Usenet archives like

<http://gd.tuwien.ac.at/faqs/faqs-hierarchy/comp/comp.lang.java.gui/>
<ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/>
<http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/>


3) Just search an archive like

<http://groups.google.com/groups?group=comp.lang.java.gui>

4) With the author's permission people have placed (sometimes older)
versions of the FAQ on web sites, too, e.g.

<http://mindprod.com/jgloss/guifaq.html>
<http://www.physci.org/guifaq.jsp>

5) There is even a Japanese translation around:

<http://homepage1.nifty.com/algafield/JavaGUIFaq19j.html>


Q1.4 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 (and many have stopped after a few weeks).


Q1.5 Does Sun support or endorse this FAQ?

No, it is just a newsgroup FAQ. Sun probably doesn't know about it.

NOTE: The author of this FAQ does not have any inside information or
contacts to Sun's Java or GUI development team and has never been
contacted by Sun. Therefore, the FAQ's author is not in a
position to forward suggestions to Sun or help with expedited
answers from Sun. Please refrain from such requests.

See also: "Q2.7 Does Sun support or endorse the newsgroup?"


Q1.6 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.7 Is there an HTML, Word, <whatever format> version of the FAQ?

There is no such official version. Some people went through the effort
to convert the FAQ to HTML. I suggest to use the

<http://txt2html.sourceforge.net>

software to create am HTML version for personal usage.

See also: "Q1.3 Where do I find a copy of the FAQ?"


Q1.8 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.9 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.10 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).


SECTION 2 - The comp.lang.java.gui Newsgroup
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Q2.1 What is the 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/[email protected]>

A longer history of comp.lang.java.* reorganizations can be found in

<ftp://ftp.isc.org/usenet/news.announce.newgroups/comp/comp.lang.ja
va-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 safe to say, that nowadays most discussions are
about Swing, plus a few about AWT and Java printing.


Q2.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:

* Issues answered in this FAQ are issues most posters don't want
to see discussed again soon.

* Posting your homework.

* Advocacy. Goto comp.lang.java.advocacy instead.

* Postings urging the readers to help. Especially in
conjunction with whining. No one in the group is paid to help
you. No one owns you anything.

* Public and hidden advertising. You think you are too clever
to be caught? Well, read this thread in our sister group
c.l.j.programmer first, and watch how some business lost all
its reputation:

http://groups.google.com/groups?threadm=58882783.
0307010403.67c54a5f%40posting.google.com

* Postings which just contain a statement like "Help! It does
not work!", without any additional information, like the
exact error message, source code, or even a hint what "it" is
supposed to mean.

* Postings demonstrating unwillingness to learn are not
welcome, too. And learning starts by reading the API
documentation before posting.

* Test messages are not welcome. Instead, use alt.test.*, and
learn how newsgroups work.

See also: "Q2.4 What is an SSCCE?"


Q2.3 Where can I find an archive of the newsgroup?

See e.g.

<http://groups.google.com/groups?group=comp.lang.java.gui>


Q2.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 your first request for help. When asked for one,
please don't complain that your source code is too large, too tricky,
too 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>


Q2.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


Q2.6 Is there more about posting to newsgroups and asking questions?

Yes, see e.g. the following for making the most out of a newsgroup
(ignore the hacker slang):

<http://www.catb.org/~esr/faqs/smart-questions.html>
[The author of that web page has requested a notice that he is not
a general help desk for all your problems].

<http://www.yoda.arachsys.com/java/newsgroups.html>

Also see the newsgroups:

<<
And RFC 1855. E.g. at

<ftp://ftp.rfc-editor.org/in-notes/rfc1855.txt>
<http://www.faqs.org/rfcs/rfc1855.html>


Q2.7 Does Sun support or endorse the newsgroup?

From time to time a poster could be spotted apparently working for
Sun's Swing development team and answering questions. But that hasn't
happened in a long time. You sometimes see announcements posted to the
group, treating the group as as write-only media. But that's it.

It is safe to say that the newsgroup isn't of much interest for Sun,
and that suggestions or informed opinions posted to the group will most
likely not be seen, noted or followed-up by Sun.

You might want to try

<http://developer.java.sun.com/developer/bugParade/>
or
<http://jcp.org/>

if you want to suggest some changes to Java. Good luck.

See also: "Q1.5 Does Sun support or endorse this FAQ?"


SECTION 3 - The Top 5 Questions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Q3.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, it is rather simple:

public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
//
// Do some time consuming task
//
...

//
// Update the GUI from within the task
// synchronous: invokeAndWait()
// asynchronous: invokeLater()
//
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//
// GUI code
//
}
});

}
}).start(); // start the thread
}

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>

SwingWorker is earmarked for inclusion into Java Standard Edition 1.6.

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().

See also: "Q3.2 How do I update the GUI from another thread?"


Q3.2 How do I update the GUI from another thread?

If you have to update the GUI from another thread (e.g. once you
offloaded a time consuming task from the EDT to another thread) you
should use the javax.swing.SwingUtilities.invokeLater() or
javax.swing.SwingUtilities.invokeAndWait(). Often you want
invokeLater().

The code is rather simple. E.g. when using an anonymous class:

SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Code to be executed on the EDT
}
}
);
// Current thread will immediately continue here

And

SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// Code to be executed on the EDT
}
}
);
// Current thread will wait until code has been executed on
// the EDT.

Again, see

<http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html>

for more details.

See also: "Q3.1 My GUI freezes or doesn't update. What to do?"


Q3.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.


Q3.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's normal drawing mode
is called 'passive rendering'. It is based on a callback mechanism.
The drawing code is supposed to sit passively there until Java asks it to
draw something by calling your paint()/paintComponent() method.

At that moment you are supposed to provide the Component with the
drawings you would like to do by using the provide Graphics/Graphics2D
drawing context. You are not supposed to "push" graphics information
into a component using getGraphics() or any other means.

This mechanism is necessary so Java can support graphics systems which
don't remember a window's 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, thus creating a resource leak.

See

<http://java.sun.com/products/jfc/tsc/articles/painting/index.html>

for more information about Java's normal painting model.

For very special cases (games, animations, slide shows, etc.), you might
want to flip to an 'active rendering' mode. Active rendering best works
when you wholly own the screen in full-screen exclusive mode.

See also: "Q4.4 What is full-screen exclusive mode?"


Q3.5 How to create a transparent or non-rectangular window?

You can't in a good, platform independent way.

Although particular Swing components can be 'transparent', the
problem is the top-level window. That window is always rectangular, and
in almost all Java implementations non-transparent.

Depending on your circumstances, platform, etc., one of the following
might (partly) work:

1) Ugly Hack, all platforms, Java 1.3+

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.

<http://www-128.ibm.com/developerworks/java/library/j-iframe/>

is a JFrame subclass which uses Robot to add transparency.

2) Windows

The nativeskin.jar of the Skin LnF at

<https://skinlf.dev.java.net/>

provides a Windows-only region feature for building non-rectangular
windows. It comes with a native Win32 library, so applications
written with this library are not portable to other platforms.

It should in principle be possible to write a similar library for
other GUI systems (e.g. X11 with the very common shape extension).

3) Apple OS X

Apple's Java for OS X observes the alpha-component of the window
background color, like one would expect from any Java
implementation. Therefore, any amount of transparency of a
top-level window can be configured by just constructing an
appropriate Color object and setting it as background color. E.g.
the following sets a completely transparent background:

window.setBackground(new Color(0, 0, 0, 0));

Non rectangular-looking windows can be constructed by

- Turning the normal window decoration of (if any), and

- Using an image (in a format which supports an alpha component,
e.g. PNG) as the window background.

4) Applet

An alternative for applets which might be good enough in some cases
can be found here:

<http://java.sun.com/docs/books/faq/src/app/MatchBackgroundExample.html>

See also: "Q6.1.2 How to create a transparent widget?"
"Q6.1.3 How to create a non-rectangular widget?"


SECTION 4 - Architecture
~~~~~~~~~~~~~~~~~~~~~~~~

Q4.1 What is this Model-View-Controller (MVC) stuff?

MVC is a way to structure an application. It is based on the idea of
separating the presentation of data from the data itself. MVC
originated in the Smalltalk world and has since then become a common
design pattern.

Swing uses a variant of MVC (not THE original MVC as Smalltalk users
will point out).

The following TSC article contains a good description of Swing's
architecture and MVC variant:

<http://java.sun.com/products/jfc/tsc/articles/architecture/index.html>


Q4.2 What is the Swing single-threading issue?

There is really no issue. With very few exceptions Swing is not thread
safe. But it can be safely used in a multi-threaded environment if the
necessary precautions are taken.

There are three simple things to take care of, not more:

1. Call all Swing API methods from the event dispatching thread
(EDT), unless the API documentation states that a method can
be called from another thread (is thread safe).

NOTE: The API documentation has been known to be wrong in
the past. Check Sun's bug parade when in doubt.

2. If you are not in the EDT, but need to call a Swing API
method, use either invokeAndWait() or invokeLater() to
schedule your code for execution on the EDT.

3. Do not block the EDT. That is, don't run time-consuming
tasks on the EDT. Instead, run these tasks in a separate
thread and use an invoke...() method to update the GUI from
that separate thread.

There is really nothing more to it.

See also: "Q3.1 My GUI freezes or doesn't update. What to do?"
"Q3.2 How do I update the GUI from another thread?"
"Q4.3 What is the right way to start a Swing GUI?"


Q4.3 What is the right way to start a Swing GUI?

Sun almost silently changed the recommended GUI startup procedure. At
the beginning of 2004 the examples in Sun's GUI tutorial were changed,
and some rather short "explanation" was given. The explanation can be
summarized as: "There is a threading bug somewhere in Swing. To work
around, already build and start the GUI from the EDT". No more useful
information is provided, e.g. if Sun knows the root cause of the bug
and intends to fix it.

So now the official way to build and start (calling setVisible(true))
the GUI is to use invokeLater(). The shortest version of a GUI
application's main() method becomes:

public static void main(String[] args) {
invokeLater(new Runnable() {
public void run() {
//
// Build and start the GUI here.
//
}
});
}

See also: "Q4.2 What is the Swing single-threading issue?"


Q4.4 What is full-screen exclusive mode?

As the name implies, a means to use the whole screen exclusively for
your applications, like it is e.g. needed for games, industrial control
applications, or slide shows. It was introduced with java 1.4.

You are much closer to the graphics hardware then in normal mode. This
requires some programming techniques which are different from normal
Swing/AWT programming. Full-screen exclusive mode is often used together
with active rendering. See

<http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html>


Q4.5 What is active rendering?

Active rendering is an a drawing method where you 'push' your graphics
on the screen instead of the usual callback-based method ('passive
rendering') where you wait until you are asked to draw something.

Active rendering results in a completely different application
architecture, and is only recommended for games, animations, etc. It
works best in full-screen exclusive mode. It is often combined with
page-flip BufferStrategy.

See also: "Q4.4 What is full-screen exclusive mode?"
"Q3.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?"



PART II
========================================================================

SECTION 5 - Window / [J]Frame / [J]Dialog (Top-Level Containers)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Q5.1 How can I ensure a window is always on top of all other windows
using AWT or Swing?

1) Before Java 1.5 you couldn't at all:

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.

2) Since Java 1.5:

You have Window.setAlwaysOnTop(), which is inherited by the other
top-level containers like JFrame. However, the implementation is
incomplete, and not supported on all platforms. There are especially
problems with a number of Unix version / Window manager version
combinations.


Q5.2 How can I (de)iconify a window?

1) Before Java 1.2 you had to revert to native calls.

2) Since Java 1.2 you can use [J]Frame.setState().

3) Since Java 1.4 you can use [J]Frame.setExtendedState(), too.
setExtendedState() provides more features than setState().


Q5.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.


Q5.4 How to 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 which you don't show, 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.


Q5.5 My modal dialog goes behind the main window. How can I ensure
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).


Q5.6 How to bind the escape key to the JD220 795362 <[email protected]>
Path: number1.nntp.dca.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!newscon06.news.prodigy.com!prodigy.net!newsfeed-00.mathworks.com!lon-transit.news.telstra.net!lon-in.news.telstra.net!news.telstra.net!news-server.bigpond.net.au!53ab2750!not-for-mail
From: "Tony Morris" <[email protected]>
Newsgroups: comp.lang.java.programmer
References: <[email protected]>
Subject: Re: Enum question
Lines: 166
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2900.2180
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2180
X-RFC2646: Format=Flowed; Original
Message-ID: <[email protected]>
Date: Tue, 14 Mar 2006 05:43:34 GMT
NNTP-Posting-Host: 61.9.214.69
X-Complaints-To: (e-mail address removed)
X-Trace: news-server.bigpond.net.au 1142315014 61.9.214.69 (Tue, 14 Mar 2006 16:43:34 EST)
NNTP-Posting-Date: Tue, 14 Mar 2006 16:43:34 EST
Organization: BigPond Internet Services
Xref: number1.nntp.dca.giganews.com comp.lang.java.programmer:795362

Larry Coon said:
I'm going to try to not be long-winded with this explanation,
but I don't know how good a job I'm going to do. Suppose I
have a bean:

public class MyBean {
String firstValue;
String secondValue;

myBean() { }

public String getFirstValue() {
return firstValue;
}
public String setFirstValue(String s) {
firstValue = s;
}
public String getSecondValue() {
return secondValue;
}
public String setSecondValue(String s) {
secondValue = s;
}
}

I'm going to display a collection of these beans in a JTable,
so I write a table model. My first inclination would be to
add a couple of static arrays with column names & widths, ie:
public static final int[] COL_WIDTHS = {30, 50};
public static final String[] COL_NAMES =
{"First value", "Second value"};

But to make it cleaner, I thought I'd use an enum:

import java.util.*;
import javax.swing.table.*;

public class MyBeanTableModel extends AbstractTableModel {
public enum Column {
FIRST_VALUE(30, "First value"),
SECOND_VALUE(50, "Second value");

private int colWidth;
private String colHeading;

Column(int colWidth, String colHeading) {
this.colWidth = colWidth;
this.colHeading = colHeading;
}

public int colWidth() { return colWidth; }
public String colHeading() { return colHeading; }

private static Column getColumn(int col) {
return Column.values()[col];
}
}

private List<MyBean> list = new ArrayList<MyBean>();

public int getPreferredWidth(int col) {
return Column.getColumn(col).colWidth();
}

public String getColumnName(int col) {
return Column.getColumn(col).colHeading();
}

public int getRowCount() {
return list.size();
}

public int getColumnCount() {
return Column.values().length;
}

public Object getValueAt(int row, int col) {
switch(col) {
case 0: return list.get(row).getFirstValue();
case 1: return list.get(row).getSecondValue();
}

return null;
}
}


I have two questions:

1. My method getColumn() in the enum seems kludgy. Is there
a better way to return a member of the enumeration based
on its ordinal position within the enumeration values?

2. My use of the case construct in getValueAt() also seems
kludgy. Is there a way to avoid the case by including the
name of the getter method in the enumeration? Something
like (this is completely invalid syntax, but hopefully it
conveys what I'm trying to accomplish):

public enum Column {
FIRST_VALUE(30, "First value", MyBean.getFirstValue),
SECOND_VALUE(50, "Second value", MyBean.getSecondValue);

private int colWidth;
private String colHeading;
private Method getter;

Column(int colWidth, String colHeading, Method method) {
this.colWidth = colWidth;
this.colHeading = colHeading;
this.method = method;
}

public Method method() {
return method;
}

// . . . .
}


then getValueAt would look something like:

public Object getValueAt(int row, int col) {
return Column.getColumn(col).method().invoke(list.get(row));
}

Thanks for any advice.


Larry Coon
University of California

I'm not sure if I understand your question, but I'm going to assume it's the
usual one regarding enums and mappings to other types.

Yes, you can provide a mapping with your enum, and even though it is
encouraged by enums themselves, it should be avoided.

Instead, declare the mapping as an interface that can exist independently of
your enum, and then write an implementation - typically backed by a Map (for
O(1) seek) and perhaps even loaded from some external resource so that it
can be changed without a recompile (if you are that way inclined and it
offers you some kind of benefit).

In your example:
interface ColumnString {
String get(Column c) throws NullPointerException;
}

Of course, you could always provide a reverse mapping or even a mapping from
some other type (besdies String).

Whatever the case, express the contractual requirement, without omission or
addition, or unwarranted (and contradictory) symbiotic relationship to some
other minimally related entity (in this case, the enum declaration).

This is all "language theory stuff" (quoted not to undermine its value) -
which Java is in complete violation of, so the premise is flawed anyway.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top