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) • • • • • •
What’s 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
JComponent
Frame JApplet
JRootPane
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 don’t 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 it’s 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
BoundedRangeModel
ButtonModel CellEditor
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 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
ScrollPaneConstants SingleSelectionModel SwingConstants UIDefaults.ActiveValue UIDefaults.LazyValue
WindowConstants
This interface provides the scrolling to 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 AbstractButton AbstractCellEditor AbstractListModel ActionMap
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
BorderFactory Box
Box.Filler BoxLayout
ButtonGroup CellRandererPane ComponentInputMap
DebugGraphics DefaultBoundedRangeModel DefaultButtonModel DefaultCellEditor DefaultComboBoxModel DefaultDesktopManager
DefaultFocusManager DefaultListCellRanderer
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. It provides the implementing the FocusManager. It implements the
default ListCellRanderer. DefaultListCellRanderer.UIResource This extends 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 andRootPaneContainer. JButton This class extends the AbstractButton and you can create the new button. JCheckBox This class extends the JToggleButton and implements the check box in which buttons are selected or deselected. JCheckBoxMenuItem It extends the JMenuItem and determines the items which is selected or deselected. JColorChooser It extends the JComponent and
JComboBox
JComponent
JDesktopPane
JDialog
JEditorPane JFileChooser JFrame JInternalFrame
JInternalFrame.JDesktopIcon JLabel JLayeredPane
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. 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.
JList JMenu
JMenuBar JMenuItem JOptionPane
JPanel JPassworkField
JPopupMenu
JPopupMenu.Separator JProgressBar
JRadioButton JRadioButtonMenuItem JRootPane
JScrollBar
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 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. JScrollPane JSeparator JSlider JSplitPane
JTabbedPane
JTable JTextArea JTextField JTextPane
JToggleButton JToggleButton.ToggleButtonModel JToolBar
JToolBar.Separator JToolTip JTree JTree.DynamicUtilTreeNode
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. It extends the DefaultButtonModel and provides theToggleButton model. It provides set of command buttons icons that performs the different actions or controls. It provides the tool bar separator. It shows the tool tips related to it's components. It shows the data in a hierarchical way. This extends the DefaultMutableTreeNode and create
JTree.EmptySelectionModel JViewPort JWindow
KeyStroke LayoutFocusTraversalPolicy
LookAndFeel
MenuSelectionManager OverlayLayout ProgressMonitor ProgressMonitorInputStream
RepaintManager ScrollPaneLayout
ScrollPaneLayout.UIResource SizeRequirements SizeSequence
children nodes. It does not allows the any selection. It gives you about the underlying information. It extends window and shows the any location or area on the desktop. It couldn't any title bar and window management buttons. This class controls the key events on the keyboard for the equivalent device. This class conducts the sorting objects according to their size, type, position or orientation. 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. It has menu selection hierarchy. The layout manager arrange the components. This class is used to monitoring the progress of any operation to be done. This class creates a progress monitor to 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
SwingUtilities Timer ToolTipManager UIDefaults UIDefaults.LazyInputMap
UIDefaults.ProxyLazyValue
UIManager UIManager.LookAndFeelInfo
ViewportLayout
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. 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 frame’s 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 ( )
Creates a new frame with no title.
JFrame (String title)
Creates a new frame with the specified title.
Method
Description
void add (Component c)
Adds the specified component to the frame.
JMenuBar getJMenuBar ( )
Gets the menu for this frame.
void pack ( )
Adjusts the size of the frame to fit the components added to it.
void remove (Component c)
void remove (Component c)
void setDefaultCloseOperation
void setIconImage (Icon image) void setLayout (LayoutManager layout)
void setLocation (int x, int y)
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. Sets the x and y position of the frame on-screen. The top-left corner of the screen is 0, 0.
void setLocationRelativeTo (Component c)
Centers the frame onscreen if the parameter is null.
void setResizeable (boolean value)
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.
void setSize (int width, int height)
void setJMenuBar(JMenuBarMenu)
Sets the menu for this frame.
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.
JButton (String text)
Creates a new button with the specified text.
Method
Description
void setBorderPainted (boolean value)
Shows or hides the button's border. The default setting is true (the border is shown).
void setContentAreaFilled (boolean value)
Specifies whether or not the button's background should be filled or left empty. The default setting is true (the background is filled in).
doClick ( )
Triggers an action event for the button as if the user clicked it.
String getText ()
Returns the text displayed by the button.
void setEnabled (boolean value)
Enables or disables the button. The default setting is true (enabled).
void setRolloverEnabled (boolean value)
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).
void setText (String text)
Sets the text displayed by the button.
void setToolTipText (String text)
Sets the tooltip text that's displayed if the user lets the mouse rest over the button.
void setVisible (boolean value)
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(); 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
Set or get the applet's content void pane. The content pane contains setContentPane(Container) the applet's visible GUI Container getContentPane() components and should be opaque. Create, set, or get the applet's root JRootPane createRootPane() pane. The root pane manages the void setRootPane(JRootPane) interior of the applet including the JRootPane getRootPane() content pane, the glass pane, and so on. Set or get the applet's menu bar to void setJMenuBar(JMenuBar) manage a set of menus for the JMenuBar getJMenuBar() 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.
Note: Although you can add component directly to JFrame or JApplet,you’ll get an error unless you turn off some error checking first,because you’re 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 they’re opened, dialog boxes and so on. From programmer’s 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 frame’s 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(); } }