Friday, February 10, 2012

Swing components and containers

Swing components and container objects

In Java, a component is the basic user interface object and is found in all Java applications. Components include lists, buttons, panels, and windows.

To use components, you need to place them in a container.
A container is a component that holds and manages other components. Containers display components using a layout manager.
Swing components inherit from the javax.Swing.JComponent class, which is the root of the Swing component hierarchy. JComponent, in turn, inherits from the Container class in the Abstract Windowing Toolkit (AWT). So Swing is based on classes inherited from AWT.
Swing provides the following useful top-level containers, all of which inherit from JComponent:


JWindow
JWindow is a top-level window that doesn't have any trimmings and can be displayed anywhere on a desktop. JWindow is a heavyweight component. You usually use JWindow to create pop-up windows and "splash" screens. JWindow extends AWT's Window class.
JFrame
JFrame is a top-level window that can contain borders and menu bars. JFrame is a subclass of JWindow and is thus a heavyweight component. You place a JFrame on a JWindow. JFrame extends AWT's Frame class.
JDialog
JDialog is a lightweight component that you use to create dialog windows. You can place dialog windows on a JFrame or JApplet. JDialog extends AWT's Dialog class.
JApplet
JApplet is a container that provides the basis for applets that run within web browsers. JApplet is a lightweight component that can contain other graphical user interface (GUI) components. JApplet extends AWT's Applet class.

All Swing components - including the JApplet and JDialog containers - need to be contained at some level inside a JWindow or JFrame.
Each top-level container depends on another intermediate container called the root, which provides a number of components to each.

JApplet is the root container for Swing applets and JFrame is the root container for a standalone GUI application.

Once you've created a root container, you can add components and other containers to it.

Each top-level container consists of the following panes:

Root pane
The root pane is an intermediate container that manages the layered pane, content pane, and glass pane. It can also manage an optional menu bar. You use a root pane to paint over multiple components or to catch input events.
 
Layered pane
The layered pane contains the content pane and the optional menu bar. It can also contain other components, which it arranges so that they overlap each other. This enables you to add pop-up menus to applications. The layered pane provides six functional layers in which you place the components you add to it. You use each of these functional layers for a specific function.
 
Content pane
The content pane holds all the visible components of the root pane, except the menu bar. It covers the visible section of the JFrame or JWindow and you use it to add components to the display area. Java automatically creates a content pane when you create a JFrame or JWindow but you can create your own content pane, which has to be opaque.
 
Glass pane
The glass pane is invisible by default but you can make it visible. When it is visible, it covers the components of the content pane, blocks all input events from reading these components, and can paint over an existing area containing one or more components.

One of the enhancements to JTabbedPane is the use of a component to represent the tab in a JTabbedPane. This new feature offers a convenient way to show several items in a small amount of space. It does this by dividing the information across separate tabs so that a user can select
  • one tab to list a particular set of components
  • a different tab to list a different set of components
By adding a Close button, you can enable the removal of the current tab from JTabbedPane.


JComponent services

JComponent is the root class for all Swing components such as JPanel, JLabel, and JButton. This class inherits from the Container class and enables you to add containers and components to an application.

The JComponent class provides the following functionality features to its subclasses:
  • Customizing component appearance
  • Checking component states
  • Adding event handling
  • Painting components
  • Modifying the containment hierarchy
  • Arranging the layout of components
  • Retrieving component size and position information
  • TextComponent Printing
Customizing component appearance
You can change the appearance of a component by setting the border, foreground color, background color, font, and a cursor to display when moving over the component.

The most commonly used methods to change the appearance of a component include the setForeground and setBackground methods, which enable you to set the colors for a component.

The setForeground method sets the color for a component's text and the setBackground method sets the color for the background areas of a component.

You can also set a component to be opaque.

For example, consider the code used to change the background color of a JLabel - called label - to black.

The code to change the background color of a label is

label.setBackground(Color.black);
 
Checking component states
The JComponent class enables you to determine the state of components.

You can add tooltips and specify names for components, using the setToolTipText and setName methods, respectively.

You can also use the isEnabled method to check whether a component is enabled to generate events from user input.

You can set a component to be visible using the setVisible method.

You can also determine whether a component is visible onscreen by using the isShowing method.
 
Adding event handling
The JComponent class provides methods that enable you to add and remove event listeners for mouse clicks, mouse movements, key presses, or component changes.

These methods include addMouseListener, addMouseMotionListener, addKeyListener, and addComponentListener.

JComponent provides a method - setTransferHandler - that you can use to enable the transfer of data using the Drag-and-Drop feature or via cut, copy, or paste functions.

You can check which component contains a specific point using the contains method. You can also determine which component lies at a specified position using the getComponentAt method.
 
Painting components
JComponent provides methods that enable you to customize painting for all its subclasses.

You can use the repaint method to repaint a component or a specific part within it.

You can refresh the layout of a component and its associated containers using the revalidate method.

However, you usually invoke this method if you change the containment hierarchy or the size of a component.
 
Modifying the containment hierarchy
You can add or remove one or more components to a container using the add and remove methods, respectively.

When adding or removing a component, you can specify the component's position in the container using the add method with an int argument. If you do not specify a component's position, it is placed at the end of the container.
 
Arranging the layout of components
You can add or remove components from a container using a layout manager or absolute position.

To specify a layout manager, you can use the setLayout and getLayout methods.

You can also specify a preferred, maximum, or minimum size of any Component object, using the setPreferredSize, setMaximumSize, and setMinimumSize methods, respectively.

Some layout managers will respect the preferred size, such as FlowLayout. Other Layout managers will ignore the preferred size, such as BorderLayout. So setting the preferredSize may not automatically yield the desired result in component size, because the layout manager will have an effect on the component sizes.

Using the layout manager enables you to set the alignment and orientation of a component. When using an absolute position, you can specify a component's location or size. To do this, you can use the setLocation and setSize methods, respectively.

You can also set the location and size using just one method, setBounds, which takes four integer parameters.
 
Retrieving component size and position information
You can retrieve information about the current width, height, size, and position of a component. To do this, you can use separate methods - getWidth, getHeight, getSize, and getLocation - or you can use the getBounds method, which retrieves all this information simultaneously.

JComponent provides a method - getInsets - that enables you to retrieve information about a component's border size.
 
TextComponent Printing
Java SE 6 simplifies the printing of the different JTextComponent elements. JTextField, JTextArea, and JTextPane contents can now be printed without any concern about pagination. This is now performed using any of the three new print methods added to the JTextComponent class.

The three new print methods are as follows:
 

 
The MessageFormat class enables you to produce concatenated messages in a language-neutral way. You should use this class to construct messages displayed for end users, that would incorporate headers and footers.
 


The printDialog method displays a dialog box and returns true if the user selects OK and false if they select Cancel. You would use this method to determine whether to attempt to print.



PrintService is an interface used to describe the capabilities of a Printer object. Using this interface, you can query the printer's supported attributes.

Attributes specifies the formats to be applied to the print job – such as double spaced or border sizes.

Interactive is used to display the current progress of a print job as well as a means to abort the current print job.


Using components and containers

All Swing applications have a containment hierarchy with a top-level container at its root to which you can add components.

For example, you can create a dialog within a JFrame container by adding a JDialog container to it via a content pane.
You use the add method to add components to all containers except JFrame and JWindow.
To add components to JFrame or JWindow, you need to add the components to the container's content pane. To do this, you retrieve the container's content pane using the getContentPane method.
Once you've added a component to a container, you need to make it visible. To do this, you use the setVisible method.
You can check whether a component is visible by using the isVisible method.
After you add components to a container, you can
  • set their size
  • specify the focus
set their size
You can use the setSize method to specify an absolute size for the component. You can also have a frame or window adjust automatically to fit all its elements by using the pack method, which ensures that the container is not smaller than its component's preferred size.
 
specify the focus
If users can interact with interface items using the mouse and keyboard, you need to ensure that the items can receive keyboard focus. By default, most components can receive focus, but you can specify this using the setFocusable method. You can also use the requestFocus method to request that a component receives focus.

Suppose that you're creating a Swing application that contains a button, a checkbox, and three radio buttons. This application prints a different message each time a user clicks one of these items.


You start by importing the Swing and AWT packages.

Next you declare a JButton called commonButton, a checkbox, a ButtonGroup called icecreams that contains the three radio buttons, and the radio buttons - radio1, radio2, and radio3.

A JButton is the Swing equivalent of a Button in AWT. It is used to provide an interface equivalent of a common button.

A JCheckBox is the Swing equivalent of the Checkbox component in AWT. This is sometimes called a ticker box, and is used to represent multiple option selections in a form.

A JRadioButton is the swing equivalent of a RadioButton in AWT. It is used to represent multiple option single selection elements in a form. This is performed by grouping the JRadio buttons using a ButtonGroup component.
You create a JFrame called frame and a JPanel - pane - to hold the contents.
Then you add a JButton. You use an action listener to determine whether the button is clicked.


Next you create the three radio buttons, add action listeners for each, and add them to the ButtonGroup.



You then create a new JPanel - radiopane - which contains the three radio buttons. Then you add the button, checkbox, and the radiopane to the pane.
And you set the focus on the commonButton button using the requestFocus method.


You create an empty JLabel named label to hold and display the message that is printed when the user clicks one of the components. You use the add method to add the label to the JPanel.


You can now add the JPanel to the JFrame. To do this, you add the JPanel to the frame's content pane.


 

You type frame.
You use the getContentPane method with the add method to add the JPanel to the JFrame. Although you can still use the getContentPane method to retrieve a java.awt.Container object, and add other components to the Container object, in Java SE 6.0 you can also call the add(Component) method against the JFrame object directly.

 


You can set the width and height of the frame by calling the setSize method. In this case, you set the width to 300 pixels and the height to 200 pixels.
And you can display the frame by setting the setVisible method to true.



You've now created a Buttons application that contains a button, a checkbox, and three radio buttons.


Creating a basic Swing application

When creating a GUI application, you can determine the look and feel of windows and frames in the application.

You need to set the look and feel for a frame before you create it. This setting affects all subsequently created JFrame.

You can customize the decoration of windows and frames in an application by using the setDefaultLookAndFeelDecorated method - a static method in the JFrame class - with a true value.

You can specify custom settings, enable full-screen exclusive mode, remove all decorations, or set an icon to represent a window.

You can also specify how each window reacts when a user clicks the Close button.
To determine what happens when a user clicks the Close button, you use the setDefaultCloseOperation method with one of the following values as an argument:
  • HIDE_ON_CLOSE
  • EXIT_ON_CLOSE
  • DISPOSE_ON_CLOSE
  • DO_NOTHING_ON_CLOSE
HIDE_ON_CLOSE
The HIDE_ON_CLOSE parameter hides the frame but doesn't exit the window. This is the default setting for JFrame and JDialog.
 
EXIT_ON_CLOSE
You use EXIT_ON_CLOSE to exit an application using the System.exit method. This value is useful for applications - especially applications with only one frame - but cannot be used with applets.
 
DISPOSE_ON_CLOSE
Specifying the DISPOSE_ON_CLOSE parameter hides the frame and frees up any resources used by it. This is the default setting for internal frames.
 
DO_NOTHING_ON_CLOSE
When you specify the DO_NOTHING_ON_CLOSE parameter, the application performs actions specified in the windowClosing method of the WindowListener object.
Event handling in Swing executes in a single thread - the event-dispatching thread. This thread ensures that event handlers are not interrupted while they are executing.
Suppose that you're building a Swing application with only one frame and one button. The application also ensures that the window exits when a user clicks the Close button.

To build a basic application, you
  • import the necessary packages
  • create and customize a top-level container and its components
  • ensure thread safety
You start by including the relevant packages. You import all the Swing classes.
Because most Swing components inherit from AWT classes, you import the awt package. You also want the application to support event handling, so you include all the AWT classes for events.



 




In the BasicSwing class, you create a createGUI method that contains the code to create and customize the top-level container, add components, and display the container.

You want the windows to use the default look and feel, so you set the setDefaultLookAndFeelDecorated method to true.
Then you create the JFrame called frame.





















After you create the JFrame, you want to ensure that the window exits when a user clicks the Close button. To do this, you use the setDefaultCloseOperation method.


 




















You type JFrame.EXIT_ON_CLOSE and press Enter.

Using the EXIT_ON_CLOSE parameter with the setDefaultCloseOperation method ensures that the window exits when the Close button is clicked.























Next you create a JPanel and a JButton. You use the JPanel to hold the contents of the container. And you add the button to the JPanel.
After adding the button to the pane, you add the JPanel to the frame.






























Once you've added the components to the top-level container, you can set its size to 220 by 200 pixels and make it visible onscreen. To do this, you use the setSize and setVisible methods, respectively.






























Once you've created and customized the container and its components, you create a main method to run and display the GUI.






























To avoid threading issues when creating and displaying the application's GUI, you want to ensure that code in the main method is executed within the event-dispatching thread.

































You type SwingUtilities.invokeLater.

You use the invokeLater method to ensure that the GUI is created on the event-dispatching thread.

You then pass a Runnable object inside the invokeLater method.

In the Runnable class, you create an instance of the BasicSwing class - called app - in the run method.

You use this instance to invoke the createGUI method.


 













 

Summary

In Java, graphical user interfaces (GUIs) consist of components and containers. Components are basic user interface objects that are contained and managed in a container. Swing is a Java-based GUI toolkit whose components are based on classes from the Abstract Windowing Toolkit (AWT).

All Swing components inherit from the JComponent class, which is a subclass of the Container class. The JComponent class enables you to customize the appearance of components, check component states, add event handling, paint components, modify the containment hierarchy, arrange the layout of components, and retrieve component size and position information.

You can add components to a container using the add method. To add components to a JFrame or JWindow, you use the getContentPane method because you add the components to the content pane. Once you've added components to a container, you use the setVisible method to make the container appear onscreen.

To build a basic Swing application, you import the necessary packages, create and customize a top-level container and components, and ensure thread-safety. You can customize windows and frames using the setDefaultLookAndFeelDecorated method. You can also determine what happens when users close windows, using the setDefaultCloseOperation method.

16 comments:

Very detailed post nicely written

100% Job Oriented R Programming Training In Chennai for more Information click to the best oracle training in chennai

This comment has been removed by the author.

100% Job Oriented R Programming Training In Chennai for more Information click to the best data -warehousing training in chennai

Easily get professional job by learning software courses from training Bangalore institute.

Great!! very well explained about java.you nailed it.

Best Core Java Training in Chennai

Great post.
It really helped me to learn something new. So thanks.
Cloud computing training in Bangalore

Great post.
It really helped me to learn something new. So thanks.

Vintage Tiles
Rustic Tiles
Mosaic Tiles

Nicely explained. Here you described the well written article from your in-depth knowledge. Truly impressive and nice information

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

I have read your blog its very attractive and impressive. I like it your blog.

ES6 Online Training JavaScript Training Courses JavaScript Training Courses | Angular 4 Online Training Angular 4 Online Training

Post a Comment