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

Swing Chapter 3. (The basics) Frames, Panels, and Borders. Easy for reading, Click here!

Custom Search
Swing Chapter 3. (The basics) Frames, Panels, and Borders. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 1/3 



Next Page (2/3) Next Page
Subpages: 1. Frames and Panels overview
2. Borders
3. Creating a custom border

Part II - The Basics

Part II consists of twelve chapters containing discussion and examples of the basic Swing components. Chapter 3 introduces frames, panels and borders, including an example showing how to create a custom rounded-edge border. Chapter 4 is devoted to layout managers with a comparison of the most commonly used layouts, a contributed section on the use of GridBagLayout, the construction of several custom layouts, and the beginnings of a JavaBeans property editing environment with the ability to change the layout manager dynamically. Chapter 5 covers labels and buttons, and presents the construction of a custom transparent polygonal button designed for use in applets, as well as a custom tooltip manager to provide proper tooltip functionality for these polygonal buttons. Chapter 6 is about using and customizing tabbed panes, including an example showing how to customize JTabbedPane and its UI delegate to build a tabbed pane which uses background images. Chapter 7 discusses scroll panes and how to customize scrolling functionality. Examples show how to use the row and column headers for tracking scroll position, how to change the speed of scrolling through implementation of the Scrollable interface, how to implement grab-and-drag scrolling, and how to programmatically invoke scrolling. Chapter 8 takes a brief look at split panes with an example showing how to base programmatic actions on the position of the divider (a gas model simulation). Chapter 9 covers combo boxes with examples showing how to build custom combo box models and cell renderers, add functionlity to the default combo box editor, and serialize a combo box model for later use. Chapter 10 is about list boxes with examples of building a custom tab-based cell renderer, adding keyboard search functionality for quick item selection, and constructing a custom checkbox cell renderer. Chapter 11 introduces the text components and undo/redo functionality with basic examples and discussions of each (text package coverage continues in chapters 19 and 20). Chapter 12 is devoted to menu bars, menus, menu items, toolbars and actions. Examples include the construction of a basic text editor with floatable toolbar, custom toolbar buttons, and a custom color chooser menu item. Chapter 13 discusses progress bars, sliders and scroll bars, including a custom scroll pane, a slider-based date chooser, a JPEG image quality editor, and an FTP client application. Chapter 14 covers dialogs, option panes, and file and color choosers. Examples demonstrate the basics of custom dialog creation and the use ofJOptionPane, as well as how to add a custom component to JColorChooser, and how to customize JFileChooser to allow multiple file selection and the addition of a custom component (a ZIP/JAR archive creation, extraction and preview tool).

Chapter 3. Frames, Panels, and Borders

In this chapter:

  •          Frames and Panels overview
  •          Borders
  •          Creating a custom border

3.1    Frames and panels overview

3.1.1    JFrame

class javax.swing.JFrame

The main container for a Swing-based application is JFrame. All objects associated with a JFrame are managed by its only child, an instance of JRootPane. JRootPane is a simple container for several child panes. When we add components to a JFrame we don't directly add them to the JFrame as we did with an AWT Frame. Instead we have to specify exactly which pane of the JFrame's JRootPane we want the component to be placed in. In most cases components are added to the contentPane by calling:

    myJFrame.getContentPane().add(myComponent);

Similarly when setting a layout for a JFrame's contents we usually just want to set the layout for the contentPane:

    myJFrame.getContentPane().setLayout(new FlowLayout());

Each JFrame contains a JRootPane as protected field rootPane. Figure 3.1 illustrates the hierarchy of a JFrame and its JRootPane. The lines in this diagram extend downward representing the "has a" relationship of each container. We will see JFrame in action soon enough.

Figure 3.1 Default JFrame and JRootPane "has a" relationship

<<file figure3-1.gif>>

3.1.2    JRootPane

class javax.swing.JRootPane

Each JRootPane contains several components referred to here by variable name: glassPane (a JPanel by default), layeredPane (a JLayeredPanel), contentPane (a JPanel by default) and menuBar (a JMenuBar).

Note: glassPane and contentPane are just variable names used by JRootPane. They are not unique Swing classes, as some explanations might lead you to believe.

Figure 3.2 glassPane

<<file figure3-2.gif>>

The glassPane is initialized as a non-opaque JPanel that sits on top of the JLayeredPane as illustrated in Figure 3.3. This component is very useful in situations where we need to intercept mouse events to display a certain cursor over the whole frame or redirect the current application focus. The glassPane can be any component but is a JPanel by default. To change the glassPane from a JPanel to another component a call to the  setGlassPane() method must be made:

    setGlassPane(myComponent);

Though the glassPane does sit on top of the layeredPane it is, by default, not visible. It can be set visible  (i.e. show itself) by calling:

    getGlassPane().setVisible(true);

The glassPane allows you to display components in front of an existing JFrame's contents. In chapter 15 we will find that can be useful as an invisible panel for detecting internal frame focus changes.

Figure 3.3 Default JFrame contents of the JLayeredPane FRAME_CONTENT_LAYER

<<file figure3-3.gif>>

The contentPane, and optional menuBar, are contained within JRootPane's layeredPane at the FRAME_CONTENT_LAYER (this is layer -30000; see chapter 15). The menuBar does not exist by default but can be set by calling the setJMenuBar() method:

    JMenuBar menu = new JMenuBar();

    setJMenuBar(menu);

When the JMenuBar is set it is automatically positioned at the top of the FRAME_CONTENT_LAYER. The rest of the layer is occupied by the contentPane as illustrated in Figure 3.3.

The contentPane is, by default, an opaque JPanel. It can be set to any other component by calling:

    setContentPane(myComponent);

Note: The default layout for the contentPane is BorderLayout. The default layout for any other JPanel is FlowLayout. Be careful not to set the layout of a JFrame directly. This will generate an exception. Setting the layout of the rootPane is also something that should be avoided because every JRootPane uses its own custom layout manager called RootLayout. We will discuss layout managers more in chapter 4.

3.1.3    RootLayout

class javax.swing.JRootPane.RootLayout

RootLayout is a layout manager built specifically to manage JRootPane's layeredPane, glassPane, and menuBar. If it is replaced by another layout manager that manager must be able to handle the positioning of these components. RootLayout is an inner class defined within JRootPane and as such, is not intended to have any use outside of this class. Thus it is not discussed in this text.

3.1.4    The RootPaneContainer interface

abstract interface javax.swing.RootPaneContainer

The purpose of the RootPaneContainer interface is to organize a group of methods that should be used to access a container's JRootPane and its different panes (see API docs). Because JFrame's main container is a JRootPane, it implements this interface (as does JFrame and JDialog). If we were to build a new component which uses a JRootPane as its main container we would most likely implement the RootPaneContainer interface. (Note that this interface exists for convenience, consistency, and organizational purposes. We are encouraged to, but certainly not required to, use it in our own container implementations.)

3.1.5    The WindowConstants interface

abstract interface javax.swing.WindowConstants

We can specify how a JFrame, JInternalFrame, or JDialog acts in response to the user closing it through use of the setDefaultCloseOperation() method. There are three possible settings, as defined by  WindowConstants interface fields:

    WindowConstants.DISPOSE_ON_CLOSE

    WindowConstants.DO_NOTHING_ON_CLOSE

    WindowConstants.HIDE_ON_CLOSE

The names are self-explanatory. DISPOSE_ON_CLOSE disposes of the JFrame and its contents,  DO_NOTHING_ON_CLOSE renders the close button useless, and HIDE_ON_CLOSE just removes the container from view. (HIDE_ON_CLOSE may be useful if we may need the conatiner, or something it contains, at a later time but do not want it to be visible until then. DO_NOTHING_ON_CLOSE is very useful as you will see below.)

3.1.6    The WindowListener interface

abstract interface java.awt.event.WindowListener

Classes that want explicit notification of window events (such as window closing, iconification, etc.) need to implement this interface. Normally the WindowAdapter class is extended instead. "When the window's status changes by virtue of being opened, closed, activated or deactivated, iconified or deiconified, the relevant method in the listener object is invoked, and the WindowEvent is passed to it."API

The methods any implementation of this interface must define are:

    void windowActivated(WindowEvent e) 

    void windowClosed(WindowEvent e) 

    void windowClosing(WindowEvent e)
    void windowDeactivated(WindowEvent e)
    void windowDeiconified(WindowEvent e)
    void windowIconified(WindowEvent e)
    void windowOpened(WindowEvent e)

3.1.7    WindowEvent

class java.awt.event.WindowEvent

The type of event used to indicate that a window has changed state. This event is passed to every WindowListener or WindowAdapter object which is registered on the source window to receive such events. Method getWindow() returns the window that generated the event. Method paramString() retreives a String describing the event type and its source, among other things.

There are six types of WindowEvents that can be generated; each is represented by the following static WindowEvent fields: WINDOW_ACTIVATED, WINDOW_CLOSED, WINDOW_CLOSING, WINDOW_DEACTIVATED, WINDOW_DEICONIFIED, WINDOW_ICONIFIED, WINDOW_OPENED.

3.1.8    WindowAdapter

abstract class java.awt.event.WindowAdapter

This is an abstract implementation of the WindowListener interface. It is normally more convenient to extend this class than to implement WindowListener directly.

Notice that none of the WindowConstants close operations actually terminate program execution. This can be accomplished by extending WindowAdapter and overriding the methods we are interested in handling (in this case just the windowClosed() method). We can create an instance of this extended class, cast it to a WindowListener object, and register this listener with the JFrame using the addWindowListener() method. This can easily be added to any application as follows:

    WindowListener l = new WindowAdapter() {

      public void windowClosing(WindowEvent e) {

        System.exit(0);

      }        

    };        

    myJFrame.addWindowListener(l);

The best method of all is to combine WindowAdapter and values from the WindowConstants interface to present the user with an exit confirmation dialog as follows:

    myJFrame.setDefaultCloseOperation(

      WindowConstants.DO_NOTHING_ON_CLOSE);

    WindowListener l = new WindowAdapter() {

      public void windowClosing(WindowEvent e) {

        int confirm = JOptionPane.showOptionDialog(myJFrame,

          "Really Exit?", "Exit Confirmation",

          JOptionPane.YES_NO_OPTION,

          JOptionPane.QUESTION_MESSAGE,

          null, null, null);

        if (confirm == 0) {

          myJFrame.dispose();

          System.exit(0);

        }

      }

    };

    myJFrame.addWindowListener(l);

Note: This can also be done for JDialog. However, to do the same thing for a JInternalFrame we must build a custom JInternalFrame subclass and implement the PropertyChangeListener interface. See chapter 16 for details.

Inserting this code into your application will always display the dialog shown in figure 3.4 when the JFrame close button is pressed. Note that this functionality is not used until later chapters in which we work with applications where closing may cause a loss of unsaved material.

Figure 3.4 Application exit confirmation dialog         

<<file figure3-4.gif>>

Reference: Dialogs and JOptionPane are discussed in Chapter 14.

3.1.9    Custom frame icons

Often we want to use a custom icon to represent our application frame. Because JFrame is a subclass of awt.Frame we can set its icon using the setIconImage() method. This method is intended to set the minimized icon to use for this frame. On some platforms this icon is also used for a title bar image (e.g. Windows).

UI Guideline: Brand Identity. Use the frame icon to establish and reinforce your brand identity. Pick a simple image which can be effective in the small space and re-used throughout the application and any accompanying material. Fig 3-5 shows the Sun Coffee Cup which was itilise as a brand mark for Java.

    ImageIcon image = new ImageIcon("spiral.gif");

    myFrame.setIconImage(image.getImage());

There is no limit to the size of the icon that can be used. A JFrame will resize any image passed to setIconImage() to fit the bound it needs. Figure 3.5 shows the top of a JFrame with a custom icon.

Figure 3.5 JFrame custom Icon         

<<file figure3-5.gif>>

3.1.10  Centering a frame on the screen

By default a JFrame displays itself in the upper left-hand corner of the screen. Often it is desirable to place it in the center of the screen. Using the getToolkit() method of the Window class (of which JFrame is a second level subclass), we can communicate with the operating system and query the size of the screen. (The Toolkit methods make up the bridge between Java components and their native, operating-system-specific, peer components.)

The getScreenSize() method gives us the information we need:

    Dimension dim = getToolkit().getScreenSize();

Figure 3.6 Screen coordinates

<<file figure3-6.gif>>

When setting the location of the JFrame, the upper left hand corner of the frame is the relevant coordinate. So to center a JFrame on the screen we need to subtract half its width and half its height from the center-of-screen coordinate:

    myJFrame.setLocation(dim.width/2 - myJFrame.getWidth()/2,

      dim.height/2 - myJFrame.getHeight()/2);

3.1.11  JApplet

class javax.swing.JApplet

JApplet is the Swing equivalent of the AWT Applet class. Like JFrame, JApplet's main child component is a JRootPane and its structure is the same. JApplet acts just like Applet and we will not go into detail about how applets work.

Reference: We suggest that readers unfamiliar with applets refer to the Java tutorial to learn more:  http://java.sun.com/docs/books/tutorial/

Several examples in later chapters are constructed as Swing applets and we will see JApplet in action soon enough. Appendix A contains information about deploying Swing-based applets for use in a browser, Java 2 applet security issues, and working with JAR archives.

3.1.12 JWindow

class javax.swing.JWindow

JWindow is very similar to JFrame except that it has no title bar, and is not resizable, minimizable, maximizable, or closable. Thus it cannot be dragged without writing custom code to do so (e.g. JToolBar's UI delegate provides this functionality for docking and undocking). We normally use JWindow to display a temporary message or splash screen logo. Since JWindow is a RootPaneContainer, we can treat it just like JFrame or JApplet when manipulating its contents.

Note: We will use JWindow to display a splash screen in several complex examples later to provide simple feedback to the user when potentially long startup times are encountered.

3.1.13  JPanel

class javax.swing.JPanel

This is the simple container component commonly used to organize a group or groups of child components inside another container. JPanel is an integral part of JRootPane, as we discussed above, and is used in each example throughout this book. Each JPanel's child components are managed by a layout manager. A layout manager controls the size and location of each child in a container. JPanel's default layout manager is FlowLayout (we will discuss this more in chapter 4). The only exception to this is JRootPane's contentPane, which is managed by a BorderLayout by default.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 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


[ 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