You are on page 1of 21

JAVA SWING

Swing is part of Java Foundation Class (JFC) library, is an extension of the AWT that has been integrated in java2.Swing Component depends on the fundamental classes defined within the java.awt package.

Java Foundation Class


AWT was modeled after HTML controls and allocates one operating System window per component. Because there are a lot more controls out there that programmers have become used to using, third parties began producing their own controls sets for use with java. When Netscape introduce its Internet Foundation Classes (IFC) library used for java and those classes become popular,Sun decided to act , and joint effort between Sun and Netscape produces original Swing as a part of JFC.( On April 2,1997)
Whats in JFC:

SWING- The large UI package Cut and paste-Clipboard support Accessibility features-Aimed at user with disability The desktop colors features-First introduce in jdk1.1 Java 2D-Improved color image nd text support Printing-Originally enable in java1.1

Swing introduced three significant advances: It uses fewer system resources. Add a lot more sophisticated component. Let you tailor the look and feel of your program.

The Swing Class Hierarchy


Object Component Container

Window Frame
JApplet JRootPane

JComponent

JLayerPane

JPanel

JFrame

JFrame

HEAVYWEIGHT vs. LIGHTWEIGTH COMPONENT

Each AWT component gets its own operating platform window (and therefore ends up looking like a standard control in the operating platform).In extended programs, a large number of such window slow performance and uses up a great deal of memory. Such component are called heavyweight. Swing is simply drawn as image in their container and dont have an operating platform window at own at all, so they use far fewer system resources. Therefore they are called lightweight. Quick Note: 1. JComponent is derived from AWT Container class, which has no heavyweight class. 2. We can mix AWT controls with swing controls(in this case AWT control appear on top of them since in swing controls are drawn on container). 3. Not all component of swing are lightweight;to display anything in a windowed environment, we need heavyweight components (windows).

4. Heavyweight classes of swing: JFrame,JDialog,JApplet and JWindow.

Swing Features
Border-we can draw border in many different style around component using setBorder method. Graphics debugging- we can use the setDebuggingGraphicsOption() method to set up graphics debugging, among other things, that you can watch each line as its drawn and make it flash. Easy Mouseless operation-easy to connect keystrokes to component. Tooltips- we use setToolTipText() method of JComponent to give component tooltip,one of those small window that appear when mouse hovers over a component. Easy scolling-we can connect scrolling to various component. Pluggable look and feel-we can set the appearance of applet and application to one of three standard looks-Windows, Motif (UNIX) or Metal(standard swing look). New layout manager-BoxLayout and OverlayLayout manager.

Classes and Interfaces


Package: javax.swing.*;

Here the following APIs interfaces and classes are available: The following interfaces and it's descriptions to be used by the Java swing. Interfaces Action Descriptions This interface performed the action with the ActionListener where the multiple controls are used for same purposes. This interface defines the data model of components like: sliders and progressBars. It defines the state model for the buttons like: radio buttons, check boxes etc. This interface used by the developer for creating the new editor and it has the new components implement interfaces. The CellEditorimplements the wrapper

BoundedRangeModel

ButtonModel CellEditor

based approach. ComboBoxEditor In this interface, the editor component used to JComboBoxcomponents. ComboBoxModel This interface represents the data model in a list model with the selected items. DesktopManager This interface has JDesktopPane object. The JInternalFrameimplements in the JDesktopPane with the help of DesktopManager. Icon This interface used to graphical representation of the components. It has fixed size picture. JComboBox.KeySelectionManager This interface has KeySelectionManager and used for the combo box data model. ListCellRenderer This interface used for paint the cell in the list with the help of "rubber stamps" . ListModel This interface used for JList components method. It gets the value of each cell of list. ListSelectionModel This interface indicates the components, which are stable or not. MenuElement This interface used where the any components are implements in the menu. MutableComboBoxModel This interface extends from the ComboBoxModel. It is a mutable version of ComboBoxModel. Renderer It defines the requirements of an object for displaying the values. RootPaneContainer This interface uses the RootPane properties and it has the components like: JFrame, JInternalFrame and JWindow etc. Scrollable This interface provides the scrolling to

ScrollPaneConstants SingleSelectionModel SwingConstants UIDefaults.ActiveValue UIDefaults.LazyValue

WindowConstants

show the large amount of data with the help of JScrollPane. This interface used for JScrollPane components. This interface used to select the one index in a model. You can set the components on the screen to own requirements. It constructs the DefaultListCellRenderer. This enables one to store an entry in the default table. The entered value is not constructed until first time is a real value is created through it usingLazyValue.createValue() method. This interface has two methods setDefaultCloseOperation and getDefaultCloseOperation and provides the window close opration.

The following classes and it's descriptions to be used by the Java swing. Classes AbstractAction Descriptions This class handles the any types of action and provides JFC Action interface. This class defines the nature of buttons and menu items. It provides a list and contents of the data model. This class defines the data model which provides the list with its contents. This class works with InputMap and performs any action when the key is

AbstractButton AbstractCellEditor AbstractListModel ActionMap

BorderFactory

Box

Box.Filler BoxLayout

ButtonGroup CellRandererPane

ComponentInputMap

DebugGraphics DefaultBoundedRangeModel DefaultButtonModel DefaultCellEditor

DefaultComboBoxModel DefaultDesktopManager

pressed. This class extends from Object and creates the Border instance in the factory. It provides the fixed spaces between two components and uses theBoxLayout object of the layout manager. This class participates in the Layout and uses the lightweight components. This class uses the arranging the multiple components either horizontally or vertically. The Box container uses this class. This class used to create the multiple buttons in a ButtonGroupobject. This class used to insert the components like: JList, JTable and JTree. This class has ComponentInputMap constructor and creates the components with the help of InpuMap. It extends from the Graphics and used to debug the graphics This class provides the implementation of default BoundedRangeModel. This class implements the generic ButtonModel. It implements the TableCellEditor and TreeCellEditor for the table and tree cells. It provides the default model for combo boxes. It implements the DesktopManager. The DesktopManager has the

JInternalFrame for creating the internal fame in a frame. DefaultFocusManager It provides the implementing the FocusManager. DefaultListCellRanderer It implements the default ListCellRanderer. DefaultListCellRanderer.UIResour This extends ce the DefaultListCellRanderer and implementing in theUIResource. DefaultListModel It extends the AbstractListModel and implementing thejava.util.Vector. DefaultListSelectionModel This class used for select the list in a data model. DefaultSingleSelectionModel This class provides the default SingleSelectionModel. FocusManager It handles all focus like: gainedFocus and lostFocus. GrayFilter It extends the RGBImageFilter and used for disabling the image through the button. ImageIcon This class implements the Icon and paints the icons from the images. InputMap This class uses the ActionMap to performed the action when you press any key of keyboard. It bounds data between the input event and an object. InputVerifier This class helps you when you works with the text fields through the focus. JApplet This class extends the Applet and implements the Accessible andRootPaneContaine r. JButton This class extends the AbstractButton and you can create the new button. JCheckBox This class extends the JToggleButton and implements the

JCheckBoxMenuItem

JColorChooser

JComboBox

JComponent

JDesktopPane

JDialog

JEditorPane

JFileChooser JFrame JInternalFrame

check box in which buttons are selected or deselected. It extends the JMenuItem and determines the items which is selected or deselected. It extends the JComponent and implementing the Accessable. Here, you choose and manipulate the colors. This class extends the JComboBox. It provides the drop-down list where user select only one item or value at a time. But combo box is a combination of multiple text or buttons etc. In java swing, All components are used the JComponent except the top-level containers like: JFrame, JDialog etc. This class extends the JLayeredPane and when you create the object of JInternalFrame to be maintained in the JDesktopPane. The JDesktopPane has DesktopManager. It extends the Dialog. This class used to create the dialog window and when you want to create the custom dialog window with the help of JOptionPane method. This class extends the JTextComponent. It edits the component by the EditorKit. This class provides the facility to choosing the file. It extends the Frame and supports the swing components architecture. This class extends from the JComponent and provides the facility to dragging, closing, resizing and menu bar of the internal frame. The JInternalFrame added into the

JDesktopPane. JInternalFrame.JDesktopIcon It displays the desktop icon and create the instance of JInternalFrame and iconify. This class used to show the small text and image. It has JFC/Swing container that can be used to overlap the components to each other. This class used to create a list where you select the one or more than objects. This class used to create a new menu where you add the JMenuItems. When you select the item then shows the popup menu items in the JMenuBar. It used to create a new menu bar where the JMenu objects are added. This class used to create new menu items in the mebus. It used to create some different types of dialog box like: message dialog box, error dialog box etc. It extends the JComponent and used to create a new panel. It provides the single line text editing. Here, don't available the original characters but view type indication characters are available. This class used to create a popup menu. It provides small window where the various types of choices are available. Here the popup menu and the separator are available. It shows the integer types values in percent within a bounded range to determine the working process. It implements the radio button and

JLabel JLayeredPane

JList JMenu

JMenuBar JMenuItem JOptionPane

JPanel JPassworkField

JPopupMenu

JPopupMenu.Separator JProgressBar

JRadioButton

JRadioButtonMenuItem JRootPane

JScrollBar

JScrollPane JSeparator JSlider

JSplitPane

JTabbedPane

JTable

JTextArea JTextField JTextPane

JToggleButton

shows the state of an item selected or deselected. It extends the JMenuItem and implements the radio button menu item This class provides the component behind the scenes by JFrame, JWindow, JDialog etc. for providing the task-orientation and functionality. This class used to create a scroll bar. It provides the view content area where you show the content to scroll this. It provides the scrollable view components. This class use the separator among the components. This class provides a control to represent a numeric value by dragging the slider. This class used to divides the two components graphically like: top and button, left and right. This class provides the tab component through which you can switch from one component to another component regarding to the specific tab button by clicking on that. It provides the user interface component and represents the two dimensional data. It provides the multi line plain text area. It provides the facility to editing the text in a single line. This class provides the component like JTexArea for multiple lines text with more capabalities. It implements two state button that

means selected or deselected. JToggleButton.ToggleButtonModelIt extends the DefaultButtonModel and provides theToggleButton model. JToolBar It provides set of command buttons icons that performs the different actions or controls. JToolBar.Separator It provides the tool bar separator. JToolTip It shows the tool tips related to it's components. JTree It shows the data in a hierarchical way. JTree.DynamicUtilTreeNode This extends the DefaultMutableTreeNode and create children nodes. JTree.EmptySelectionModel It does not allows the any selection. JViewPort It gives you about the underlying information. JWindow It extends window and shows the any location or area on the desktop. It couldn't any title bar and window management buttons. KeyStroke This class controls the key events on the keyboard for the equivalent device. LayoutFocusTraversalPolicy This class conducts the sorting objects according to their size, type, position or orientation. LookAndFeel It provides the dramatically changes in the component like frame related to the graphics for the application. Through this the application can be done very efficient and easier. MenuSelectionManager It has menu selection hierarchy. OverlayLayout The layout manager arrange the components. ProgressMonitor This class is used to monitoring the progress of any operation to be done. ProgressMonitorInputStream This class creates a progress monitor to

RepaintManager ScrollPaneLayout

ScrollPaneLayout.UIResource SizeRequirements SizeSequence SwingUtilities Timer ToolTipManager UIDefaults

UIDefaults.LazyInputMap

UIDefaults.ProxyLazyValue

UIManager UIManager.LookAndFeelInfo

monitor the progress of reading input from the input stream. It cleanups all the rights when the stream is closed. This class manage and override the repaint requests. It implements the LayoutManager and manage the components like: scroll bar, row header, column header etc. It extends the ScrollPaneLayout and implements the UIResource. It calculates the size and positions of components. It represents the order list of size and it's positions. This class has utilities methods for swing. Actions perform the predefined rate. It manages the all tool tips. It extends the Hashtable and you set/get the value with the help of UIManager. This class creates a Input Map through it's createValue() method. The array of key after binding is passed to the constructor of this. Example of binding of key is array of pressing key information (e.g. ctrl + c or alt + f). This class is used to create a lazy value which is used to delay loading of the class to create instance for that. This class has track of the current look and feel details. This is the nested class of UIManager class i.e. used for getting information about all the look and feels installed with the softwaredevelopment kit.

ViewportLayout

It implements the LayoutManager and defines the policy for the layout.

The following Exceptions and it's description to be used by the Java swing. Exception Descriptions

This exception occurred when the look UnsupportedLookAndFeelException and feel classes are not supported to user's system.

JFrame
Package:javax.swing JFrame is an abstract class It is heavyweight component

The content pane was introduced in swing to deal with the complexities which are involved in making heavyweight and lightweight component work together. The components added to frames content pane instead of adding them directly to the frame itself. Steps: 1. create JFrame object 2. Get content pane 3. add component to content pane. Example: JFrame o=new JFrame(); Container cpane=o.getContentPane(); Cpane.add(<Somecomponent>); Constructor Description

JFrame ( ) JFrame (String title) Method void add (Component c)

Creates a new frame with no title. Creates a new frame with the specified title. Description Adds the specified component to the frame. Gets the menu for this frame. Adjusts the size of the frame to fit the components added to it. Removes the specified component from the frame. Removes the specified component from the frame. Sets the action taken when the user closes the frame. Always specify JFrame.EXIT ON CLOSE. Sets the icon displayed when the frame is minimized. Sets the layout manager used to control how components are arranged when the frame is displayed. The default is the BorderLayout manager.

JMenuBar getJMenuBar ( ) void pack ( )

void remove (Component c)

void remove (Component c)

void setDefaultCloseOperation

void setIconImage (Icon image) void setLayout (LayoutManager layout)

void setLocation (int x, int y)

Sets the x and y position of the frame on-screen. The top-left corner of the screen is 0, 0. Centers the frame onscreen if the parameter is null. Sets whether or not the size of the frame can be changed by the user. The default setting is true (the frame can be resized). Sets the size of the frame to the specified width and height. Sets the menu for this frame.

void setLocationRelativeTo (Component c)

void setResizeable (boolean value)

void setSize (int width, int height)

void setJMenuBar(JMenuBarMenu)

JPanel
Package: javax.swing.JPanel It used to group components within one area of an applet or a frame Steps: 1. Create JFrame object 2. Create JPanel object 3. Add all component to the JPanel object by using add() method 4. An intermediate JPanel object is made part of content pane using setContentPane() method of JFrame class Example: JFrame o=new JFrame(); JPanel pnl=new JPanel(); pnl.add(<Somecomponent>); o.setContentPane(pnl); Constructor Description

JButton ( )

Creates a new button with no initial text. Creates a new button with the specified text. Description Shows or hides the button's border. The default setting is true (the border is shown). Specifies whether or not the button's background should be filled or left empty. The default setting is true (the background is filled in). Triggers an action event for the button as if the user clicked it. Returns the text displayed by the button. Enables or disables the button. The default setting is true (enabled). Enables or disables the rollover effect, which causes the border to get thicker when the mouse moves over the button. The default setting is true (rollover effect enabled). Sets the text displayed by the button.

JButton (String text)

Method void setBorderPainted (boolean value)

void setContentAreaFilled (boolean value)

doClick ( )

String getText ()

void setEnabled (boolean value)

void setRolloverEnabled (boolean value)

void setText (String text)

void setToolTipText (String text) void setVisible (boolean value)

Sets the tooltip text that's displayed if the user lets the mouse rest over the button. Shows or hides the button. The default setting is true (the button is visible).

JApplet
Swing applet represent by class JApplet. Package:javax.swing.* Like JFrame the components are first added to the contentpane Example: Container cpane=this.getContentPane(); cpane.setLayout(<LayoutObject>); cpane.add(<some component>);

Painting in Swing and AWT

Swing itself uses paint() method to draw the border around the component as well as to draw any child component inside the component and other task. Instead of using paint() method ,in swing swing we can use paintComponet() method.

The JApplet API


Method Purpose

void setContentPane(Container) Container getContentPane()

JRootPane createRootPane() void setRootPane(JRootPane) JRootPane getRootPane() void setJMenuBar(JMenuBar)

Set or get the applet's content pane. The content pane contains the applet's visible GUI components and should be opaque. Create, set, or get the applet's root pane. The root pane manages the interior of the applet including the content pane, the glass pane, and so on. Set or get the applet's menu bar to

manage a set of menus for the frame. void setGlassPane(Component) Set or get the applet's glass pane. You can use the glass pane to Component getGlassPane() intercept mouse events. Set or get the applet's layered void pane. You can use the frame's setLayeredPane(JLayeredPane) layered pane to put components JLayeredPane getLayeredPane() on top of or behind other components. JMenuBar getJMenuBar()

Note: Although you can add component directly to JFrame or JApplet,youll get an error unless you turn off some error checking first,because youre expected to add them to the content pane in the JRootPane object The root pane and its member are all consider being fundamental in Swing Container Design. JRootpane

GlassPane

LayeredPane

Glass pane: The Glass pane is used to draw over an area that already contains some components.A glass pane also be used to catch mouse events. Layered pane: The layered pane of class JLayeredPane,is where most of action takes place. There are specific layers to which you have access that display menus when theyre opened, dialog boxes and so on. From programmers point of view ,probably the most interesting lauered pane are content pane and menu bar

Content pane:

The content pane was introduced in swing to deal with the complexities which are involved in making heavyweight and lightweight component work together. The components added to frames content pane instead of adding them directly to the frame itself. JMenubar: If you have menu bar in you program.it's supported with a JMenuBar object,which display right above the content pane.

Example:

import java.awt.*; import java.awt.event.*; import javax.swing.*; class demo extends JFrame implements ItemListener { JRadioButton c1,c2,c3; ButtonGroup grp; Container con; demo() { grp=new ButtonGroup(); c1=new JRadioButton("GREEN",false); c2=new JRadioButton("RED",true); c3=new JRadioButton("BLUE",false); con=this.getContentPane(); setSize(500,500); setTitle("demo"); setVisible(true);

setLayout(new FlowLayout()); con.setBackground(Color.red); c1.setToolTipText("Choice Green"); c2.setToolTipText("Choice Red"); c3.setToolTipText("Choice Blue"); grp.add(c1); grp.add(c2); grp.add(c3); con.add(c1); con.add(c2); con.add(c3); c1.addItemListener(this); c2.addItemListener(this); c3.addItemListener(this); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void itemStateChanged(ItemEvent e) { if(e.getItemSelectable()==c1) con.setBackground(Color.green); if(e.getItemSelectable()==c2) con.setBackground(Color.red); if(e.getItemSelectable()==c3) con.setBackground(Color.blue); } public static void main(String[] cb) { demo o=new demo(); } }

Swing advantages
Swing provides a richer set of components than AWT. They are 100% Java-based. AWT on the other hand was developed with the mind set that if a component or capability of a component wasn't available on one platform, it won't be available on any platform. Something quickly portable from platform x, to y, to z. Due to the peer-based nature of AWT, what might work on one implementation might not work on another, as the peer-integration might not be as robust. Many of the original AWT problems were traceable to differences in peer implementations. This is not to say that there are less bugs in Swing, though most are out these days. Its just that if a bug exists in Swing, its the same problem on all platforms, which was not the case with AWT. [FAQ Manager Note] There are a few other advantages to Swing over AWT: Swing provides both additional components and added functionality to AWTreplacement components Swing components can change their appearance based on the current "look and feel" library that's being used. You can use the same look and feel as the platform you're on, or use a different look and feel Swing components follow the Model-View-Controller paradigm (MVC), and thus can provide a much more flexible UI. Swing provides "extras" for components, such as: o Icons on many components o Decorative borders for components o Tooltips for components Swing components are lightweight (less resource intensive than AWT) Swing provides built-in double buffering Swing provides paint debugging support for when you build your own components

Swing also has a few disadvantages: It requires Java 2 or a separate JAR file If you're not very careful when programming, it can be slower than AWT (all components are drawn) Swing components that look like native components might not act exactly like native components

Other swing disadvantage Be carefull, swing is not thread safe. You can get into trouble if you modify the model concurrently with the screen updater thread.

You might also like