Home » Desktop Java » swing » JAVA Swing Component Tutorial

About Jyoti Jha

Jyoti Jha
Jyoti is a tech enthusiast and is an avid programmer. She holds a post graduation degree in (M.Tech) Computer Science Engineering from Thapar Univeristy, Patiala, India. Post her graduate studies, she has worked in Software companies such as SLK Software and Aricent, India as Software Engineer in various projects primarily in the field of Requirement analysis and design, implementing new algorithms in C++ and JAVA used in ISDN network and designing databases and. She is inquisitive about socio economic reforms as well as advancement in technical fronts and keep herself informed with TED talks and various blogs.

JAVA Swing Component Tutorial

 

1. Introduction

Swing API is a set of extensible GUI Components to ease developer’s life to create JAVA based Front End/ GUI Applications. It is build upon top of AWT API and acts as replacement of AWT API as it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criteria.

  • A single API is to be sufficient to support multiple look and feel.
  • API is to model driven so that highest level API is not required to have the data.
  • API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers to use it.

2. JAVA Swing Components

2.1 Setup

Popular Java Editors:
To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:

  • Notepad: On Windows machine you can use any simple text editor like Notepad TextPad.
  • NetBeans: is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
  • Eclipse: is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org

Prerequisite
This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link click here.

2.2 Using Java Swing Components

This lesson gives you the background information you need to use the Swing components, and then describes every Swing component. It assumes that you have successfully compiled and run a program that uses Swing components, and that you are familiar with basic Swing concepts.

2.2.1 Using Top Level Containers

It discusses how to use the features shared by the JFrame, JDialog, and JApplet classes — content panes, menu bars, and root panes. It also discusses the containment hierarchy, which refers to the tree of components contained by a top-level container.

To appear onscreen, every GUI component must be part of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container as its root. We’ll show you one in a bit.

  • Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second.
  • Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container’s GUI.
  • You can optionally add a menu bar to a top-level container. The menu bar is by convention positioned within the top-level container, but outside the content pane. Some look and feels, such as the Mac OS look and feel, give you the option of placing the menu bar in another place more appropriate for the look and feel, such as at the top of the screen.

Here are the topics this section discusses:

Top-Level Containers and Containment Hierarchies
Each program that uses Swing components has at least one top-level container. This top-level container is the root of a containment hierarchy — the hierarchy that contains all of the Swing components that appear inside the top-level container.

As a rule, a standalone application with a Swing-based GUI has at least one containment hierarchy with a JFrame as its root. For example, if an application has one main window and two dialogs, then the application has three containment hierarchies, and thus three top-level containers. One containment hierarchy has a JFrame as its root, and each of the other two has a JDialog object as its root.

A Swing-based applet has at least one containment hierarchy, exactly one of which is rooted by a JApplet object. For example, an applet that brings up a dialog has two containment hierarchies. The components in the browser window are in a containment hierarchy rooted by a JApplet object. The dialog has a containment hierarchy rooted by a JDialog object.

Adding Components to the Content Pane
Here’s the code that the preceding example uses to get a frame’s content pane and add the yellow label to it:

SwingComponentExample.java

/In initialization code:
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);

As the code shows, you find the content pane of a top-level container by calling the getContentPane method. The default content pane is a simple intermediate container that inherits from JComponent, and that uses a BorderLayout as its layout manager.

It’s easy to customize the content pane — setting the layout manager or adding a border, for example. However, there is one tiny gotcha. The getContentPane method returns a Container object, not a JComponent object. This means that if you want to take advantage of the content pane’s JComponent features, you need to either typecast the return value or create your own component to be the content pane. Our examples generally take the second approach, since it’s a little cleaner. Another approach we sometimes take is to simply add a customized component to the content pane, covering the content pane completely.

Note that the default layout manager for JPanel is FlowLayout; you’ll probably want to change it.

To make a component the content pane, use the top-level container’s setContentPane method. For example:

SwingComponentExample.java

/In initialization code
//Create a panel and add components to it.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(someBorder);
contentPane.add(someComponent, BorderLayout.CENTER);
contentPane.add(anotherComponent, BorderLayout.PAGE_END);


topLevelContainer.setContentPane(contentPane);

Adding a Menu Bar
In theory, all top-level containers can hold a menu bar. In practice, however, menu bars usually appear only in frames and applets. To add a menu bar to a top-level container, create a JMenuBar object, populate it with menus, and then call setJMenuBar. The TopLevelDemo adds a menu bar to its frame with this code:

frame.setJMenuBar(greenMenuBar);

2.2.2 The JComponent Class

With the exception of top-level containers, all Swing components whose names begin with “J” descend from the JComponent class. For example, JPanel, JScrollPane, JButton, and JTable all inherit from JComponent. However, JFrame and JDialog don’t because they implement top-level containers.

The JComponent class extends the Container class, which itself extends Component. The Component class includes everything from providing layout hints to supporting painting and events. The Container class has support for adding components to the container and laying them out. This section’s API tables summarize the most often used methods of Component and Container, as well as of JComponent.

JComponent Features
The JComponent class provides the following functionality to its descendants:

    • Tool tips: By specifying a string with the setToolTipText method, you can provide help to users of a component. When the cursor pauses over the component, the specified string is displayed in a small window that appears near the component.
    • Painting and borders: The setBorder method allows you to specify the border that a component displays around its edges. To paint the inside of a component, override the paintComponent method.
    • Application-wide pluggable look and feel: Behind the scenes, each JComponent object has a corresponding ComponentUI object that performs all the drawing, event handling, size determination, and so on for that JComponent. Exactly which ComponentUI object is used depends on the current look and feel, which you can set using the UIManager.setLookAndFeel method.
    • Custom properties: You can associate one or more properties (name/object pairs) with any JComponent. For example, a layout manager might use properties to associate a constraints object with each JComponent it manages. You put and get properties using the putClientProperty and getClientProperty methods
    • Support for layout: Although the Component class provides layout hint methods such as getPreferredSize and getAlignmentX, it doesn’t provide any way to set these layout hints, short of creating a subclass and overriding the methods. To give you another way to set layout hints, the JComponent class adds setter methods — setMinimumSize, setMaximumSize, setAlignmentX, and setAlignmentY.
    • Support for accessibility

The JComponent class provides API and basic functionality to help assistive technologies such as screen readers get information from Swing components.

    • Support for drag and drop

The JComponent class provides API to set a component’s transfer handler, which is the basis for Swing’s drag and drop support.

    • Double buffering

Double buffering smooths on-screen painting.

    • Key bindings

This feature makes components react when the user presses a key on the keyboard. For example, in many look and feels when a button has the focus, typing the Space key is equivalent to a mouse click on the button. The look and feel automatically sets up the bindings between pressing and releasing the Space key and the resulting effects on the button

2.3 The JComponent API

The JComponent class provides many new methods and inherits many methods from Component and Container. The following tables summarize the methods we use the most

2.3.1 Customizing Component Appearance

Constructor or MethodPurpose
void setBorder(Border)
Border getBorder()
Set or get the border of the component.
void setForeground(Color)
void setBackground(Color)
Set the foreground or background color for the component. The foreground is generally the color used to draw the text in a component. The background is (not surprisingly) the color of the background areas of the component, assuming that the component is opaque.
Color getForeground()
Color getBackground()
Get the foreground or background color for the component.
void setOpaque(boolean)
boolean isOpaque()
Set or get whether the component is opaque. An opaque component fills its background with its background color.
void setFont(Font)
Font getFont()
Set or get the component’s font. If a font has not been set for the component, the font of its parent is returned.
void setCursor(Cursor)
Cursor getCursor()
Set or get the cursor displayed over the component and all components it contains (except for children that have their own cursor set). Example: aPanel.setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR))

2.3.2 Setting and Getting Component State

Constructor or MethodPurpose
void setComponentPopupMenu(JPopupMenu)Sets the JPopupMenu for this JComponent. The UI is responsible for registering bindings and adding the necessary listeners such that the JPopupMenu will be shown at the appropriate time. When the JPopupMenu is shown depends upon the look and feel: some may show it on a mouse event, some may enable a key binding.

If popup is null, and getInheritsPopupMenu returns true, then getComponentPopupMenu will be delegated to the parent. This provides for a way to make all child components inherit the popupmenu of the parent.

void setTransferHandler(TransferHandler)
TransferHandler getTransferHandler()
Set or remove the transferHandler property. The TransferHandler supports exchanging data via cut, copy, or paste to/from a clipboard as well a drag and drop.
void setToolTipText(String)Set the text to display in a tool tip.
void setName(String)
String getName()
Set or get the name of the component. This can be useful when you need to associate text with a component that does not display text.
boolean isShowing()Determine whether the component is showing on screen. This means that the component must be visible, and it must be in a container that is visible and showing.
void setEnabled(boolean)
boolean isEnabled()
Set or get whether the component is enabled. An enabled component can respond to user input and generate events.
void setVisible(boolean)
boolean isVisible()
Set or get whether the component is visible. Components are initially visible, with the exception of top-level components.

2.3.3 Handling Events

Constructor or MethodPurpose
void addHierarchyListener(hierarchyListener l)
void removeHierarchyListener(hierarchyListener l)
Adds or removes the specified hierarchy listener to receive hierarchy changed events from this component when the hierarchy to which this container belongs changes. If listener l is null, no exception is thrown and no action is performed.
void addMouseListener(MouseListener)
void removeMouseListener(MouseListener)
Add or remove a mouse listener to or from the component. Mouse listeners are notified when the user uses the mouse to interact with the listened-to component.
void addMouseMotionListener(MouseMotionListener)
void removeMouseMotionListener(MouseMotionListener)
Add or remove a mouse motion listener to or from the component. Mouse motion listeners are notified when the user moves the mouse within the listened-to component’s bounds.
void addKeyListener(KeyListener)
void removeKeyListener(KeyListener)
Add or remove a key listener to or from the component. Key listeners are notified when the user types at the keyboard and the listened-to component has the keyboard focus.
void addComponentListener(ComponentListener)
void removeComponentListener(ComponentListener)
Add or remove a component listener to or from the component. Component listeners are notified when the listened-to component is hidden, shown, moved, or resized.
boolean contains(int, int)
boolean contains(Point)
Determine whether the specified point is within the component. The argument should be specified in terms of the component’s coordinate system. The two int arguments specify x and y coordinates, respectively.
Component getComponentAt(int, int)
Component getComponentAt(Point)
Return the component that contains the specified x, y position. The top-most child component is returned in the case where components overlap. This is determined by finding the component closest to the index 0 that claims to contain the given point via Component.contains().

2.3.4 Painting Components

MethodPurpose
void repaint()
void repaint(int, int, int, int)
Request that all or part of the component be repainted. The four int arguments specify the bounds (x, y, width, height, in that order) of the rectangle to be painted.
void repaint(Rectangle)Request that the specified area within the component be repainted.
void revalidate()Request that the component and its affected containers be laid out again. You should not generally need to invoke this method unless you explicitly change a component’s size/alignment hints after it’s visible or change a containment hierarchy after it is visible. Always invoke repaint after revalidate.
void paintComponent(Graphics)Paint the component. Override this method to implement painting for custom components.

3. Output

The Output of the code when executed will look like the one below.

SwingComponentExample

SwingComponentExample

4. Downloads

This was an example of creation of JAVA Swing Component.

Download
You can download the full source code of this example here: SwingComponentExample
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of