Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Chapter 2. (Introduction) Swing Mechanics. Easy for reading, Click here!

Chapter 2. (Introduction) Swing Mechanics. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 1/14 


Next Page (2/14) Next Page

Chapter 2. Swing Mechanics

In this chapter:

Subpages: 1. JComponent properties, size, and positioning 
2.  Event handling and dispatching 
3. Multithreading
4. Timers
5. AppContext service
6. Inside Timers & the TimerQueue
7. JavaBeans architecture
8. Fonts, Colors, Graphics and text
9. Using the Graphics clipping area
10. Graphics debugging
11. Painting and validation
12. Focus Management
13. Keyboard input, KeyStrokes, and Actions
14. SwingUtilities

2.1    JComponent properties, size, and positioning

2.1.1    Properties

All Swing components conform to the JavaBeans specification. In section 2.7 we will discuss this in detail. Among the five features a JavaBean is expected to support is a set of properties and associated accessor methods. A property is a global variable, and its accessor methods, if any, are normally of the form setPropertyname(), getPropertyname() or isPropertyname().

A property that has no event firing associated with a change in its value is called a simple property. A bound property is one for which PropertyChangeEvents are fired after it changes state. We can register PropertyChangeListeners to listen for PropertyChangeEvents through JComponent's addPropertyChangeListener() method. A constrained property is one for which PropertyChangeEvents are fired before a change in state occurs. We can register VetoableChangeListeners to listen for PropertyChangeEvents through JComponent's addVetoableChangeListener() method. A change can be vetoed in the event handling code of a VetoableChangeListener by throwing a PropertyVetoException. (There is only one Swing class with constrained properties: JInternalFrame).

Note: Each of these event and listener classes is defined in the java.awt.beans package.

PropertyChangeEvent's carry three pieces of information with them: name of the property, old value, and new value. Beans can use an instance of PropertyChangeSupport to manage the dispatching of PropertyChangeEvents corresponding to each bound property, to each registered listener. Similarly, an instance of VetoableChangeSupport can be used to manage the sending of all PropertyChangeEvents corresponding to each constrained property.

Swing introduces a new class called SwingPropertyChangeSupport (defined in javax.swing.event) which is a subclass of, and almost identical to, PropertyChangeSupport. The difference is that SwingPropertyChangeSupport has been built to be more efficient. It does this by sacrificing thread safety, which, as we will see later in this chapter, is not an issue in Swing if the multithreading guidelines are followed consistently (because all event processing should occur on only one thread--the event-dispatching thread). So if we are confident that our code has been constructed in a thread-safe mannar, we are encouraged to use this more efficent version, rather than PropertyChangeSupport.

Note: There is no Swing equivalent of VetoableChangeSupport because there are currently only four constrained properties in Swing--all defined in JInternalFrame.

Swing also introduces a new type of property which we will call a change property, for lack of a given name. We use ChangeListeners to listen for ChangeEvents that get fired when these properties change state. A ChangeEvent only carries one piece of information with it: the source of the event. For this reason, change properties are less powerful than bound or constrained properties, but they are more widespread. A JButton, for instance, sends change events whenever it is armed (pressed for the first time), pressed, and released (see chapter 5).

Another new property-like feature Swing introduces is the notion of client properties. These are basically key/value pairs stored in a Hashtable provided by each Swing component. This allows properties to be added and removed at run-time, and is often a convenient place to store data without having to build a separate subclass.

Warning: Client properties may seem like a great way to add property change support for custom components, but we are explicitly advised against this: "The clientProperty dictionary is not intended to support large scale extensions to JComponent nor should it be considered an alternative to subclassing when designing a new component."API

Client properties are bound properties: when a client property changes, a PropertyChangeEvent is dispatched to all registered PropertyChangeListeners. To add a property to a component's client properties Hashtable, we do the following:

    myComponent.putClientProperty("myname", myValue);

To retrieve a client property:

    myObject = myComponent.getClientProperty("myname");

To remove a client propery we can provide a null value:

    myComponent.putClientProperty("myname", null);

For example, JDesktopPane uses a client property to control the outline dragging mode for JInternalFrames (this will work no matter which L&F is in use):

    myDesktop.putClientProperty("JDesktopPane.dragMode", "outline");

Note: You can always find out which properties have change events associated with them, as well as any other type of event, by referencing to the Swing source code. Unless you are using Swing for simple interfaces, we strongly suggest getting used to this.

Five Swing components have special client properties that only the Metal L&F pays attention to. Briefly these are:

  JTree.lineStyle

A String used to specify whether node relationships are displayed as angular connecting lines ("Angled"), horizontal lines defining cell boundaries ("Horizontal" -- default), or no lines at all ("None").

  JScrollBar.isFreeStanding

A Boolean value used to specify whether all sides of a JScrollbar will have an etched border (Boolean.FALSE -- default) or only the top and left edges (Boolean.TRUE).

  JSlider.isFilled

A Boolean value used to specify whether the lower portion of a slider should be filled (Boolean.TRUE) or not (Boolean.FALSE -- default).

  JToolBar.isRollover

A Boolean value used to specify whether a toolbar button displays an etched border only when the mouse is within its bounds and no border if not (Boolean.TRUE), or always use an etched border (Boolean.FALSE -- default).

  JInternalFrame.isPalette

A Boolean value used to specify whether a very thin border is used (Boolean.TRUE) or the regular border is used (Boolean.FALSE -- default). As of Java 2 FCS this property is not used.

2.1.2    Size and positioning

Because JComponent extends java.awt.Container it inherits all the sizing and positioning functionality we are used to. We are encouraged to manage a component's preferred, minimum, and maximum sizes using the following methods:

  setPreferredSize(), getPreferredSize()

The most comfortable size of a component. Used by most layout managers to size each component.

  setMinimumSize(), getMinimumSize()

Used during layout to act as a lower bounds for a component's dimensions.

  setMaximumSize(), getMaximumSize()

Used during layout to act as an upper bounds for a component's dimensions.

Each setXX()/getXX() method accepts/returns a Dimension instance. We will learn more about what these sizes mean in terms of each layout manager in chapter 4. Whether or not a layout manager pays attention to these sizes is solely based on that layout manager's implementation. It is perfectly feasible to construct a layout manager that simply ignores all of them, or pays attention to only one. The sizing of components in a container is layout-manager specific.

JComponent's setBounds() method can be used to assign a component both a size and a position within its parent container. This overloaded method can take either a Rectangle parameter (java.awt.Rectangle) or four int paramaters representing x-coordinate, y-coordinate, width, and height. For example, the following two are equivalent:

    myComponent.setBounds(120,120,300,300);

    Rectangle rec = new Rectangle(120,120,300,300);

    myComponent.setBounds(rec);

Note that setBounds() will not override any layout policies in effect due to a parent container's layout manager. For this reason a call to setBounds() may appear to have been ignored in some situations because it tried to do its job and was forced back to its original size by the layout manager (layout managers always have first crack at setting the size of a component).

setBounds() is commonly used to manage child components in containers with no layout manager (such as JLayeredPane, JDesktopPane, and JComponent itself). For instance, we normally use setBounds() when adding a JInternalFrame to a JDesktopPane.

A component's size can safely be queried in typical AWT style, such as:

    int h = myComponent.getHeight();

    int w = myComponent.getWidth();

Size can also be retrieved as a Rectangle or a Dimension instance:

    Rectangle rec2 = myComponent.getBounds();

    Dimension dim = myComponent.getSize();

Rectangle contains four publically accessible properties describing its location and size:

    int recX = rec2.x;

    int recY = rec2.y;

    int recWidth = rec2.width;

    int recHeight = rec2.height;

Dimension contains two publically accessible properties describing size:

    int dimWidth = dim.width;

    int dimHeight = dim.height;

The coordinates returned in the Rectangle instance using getBounds() represent a component's location within its parent. These coordinates can also be obtained using the getX() and getY() methods. Additionaly, we can set a component's position within its container using the setLocation(int x, int y) method.

JComponent also maintains an alignment. Horizontal and vertical alignments can be specified by float values between 0.0 and 1.0: 0.5 means center, closer to 0.0 means left or top, and closer to 1.0 means right or bottom. The corresponding JComponent methods are:

    setAlignmentX(float f);

    setAlignmentY(float f);

These values are only used in containers managed by BoxLayout and OverlayLayout.



[ Return to Swing (Book) ]


Search Books
Custom Search
Latest articles
 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 2


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy