Java Swing

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

description

easy tutorial for java swing

Transcript of Java Swing

Page 1: Java Swing

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.

Page 2: Java Swing

The Swing Class Hierarchy

HEAVYWEIGHT vs. LIGHTWEIGTH COMPONENTEach 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

Object

Frame

JComponentWindow

Container

Component

JFrame

JFrameJRootPane JLayerPane JPanelJApplet

Page 3: Java Swing

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 DescriptionsAction This interface performed the action

with the ActionListener where the multiple controls are used for same purposes.

BoundedRangeModel This interface defines the data model of components like: sliders and progressBars.

ButtonModel It defines the state model for the buttons like: radio buttons, check boxes etc.

CellEditor This interface used by the developer for creating the new editor and it has the new components implement interfaces. The CellEditorimplements the

Page 4: Java Swing

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. 

Page 5: Java Swing

Scrollable This interface provides the scrolling to show the large amount of data with the help of JScrollPane.

ScrollPaneConstants This interface used for JScrollPane components.

SingleSelectionModel This interface used to select the one index in a model.

SwingConstants You can set the components on the screen to own requirements.

UIDefaults.ActiveValue It constructs the DefaultListCellRenderer.

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

WindowConstants 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 DescriptionsAbstractAction This class handles the any types of

action and provides JFC Action interface.

AbstractButton This class defines the nature of buttons and menu items.

AbstractCellEditor It provides a list and contents of the data model.

AbstractListModel This class defines the data model which provides the list with its

Page 6: Java Swing

contents.ActionMap This class works with InputMap and

performs any action when the key is pressed.

BorderFactory This class extends from Object and creates the Border instance in the factory.

Box It provides the fixed spaces between two components and uses theBoxLayout object of the layout manager.

Box.Filler This class participates in the Layout and uses the lightweight components.

BoxLayout This class uses the arranging the multiple components either horizontally or vertically. The Box container uses this class.

ButtonGroup This class used to create the multiple buttons in a ButtonGroupobject.

CellRandererPane This class used to insert the components like: JList, JTable and JTree.

ComponentInputMap This class has ComponentInputMap constructor and creates the components with the help of InpuMap.

DebugGraphics It extends from the Graphics and used to debug the graphics

DefaultBoundedRangeModel This class provides the implementation of default BoundedRangeModel.

DefaultButtonModel This class implements the generic ButtonModel.

DefaultCellEditor It implements the TableCellEditor and TreeCellEditor for the table and tree cells.

DefaultComboBoxModel It provides the default model for combo boxes.

Page 7: Java Swing

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

Page 8: Java Swing

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 implementing the Accessable. Here, you choose and manipulate the colors.

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

JComponent In java swing, All components are used the JComponent except the top-level containers like: JFrame, JDialog etc.

JDesktopPane This class extends the JLayeredPane and when you create the object of JInternalFrame to be maintained in the JDesktopPane. The JDesktopPane has DesktopManager.

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

JEditorPane This class extends the JTextComponent. It edits the component by the EditorKit.

JFileChooser This class provides the facility to choosing the file.

JFrame It extends the Frame and supports the swing components architecture.

Page 9: Java Swing

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

JLabel This class used to show the small text and image.

JLayeredPane It has JFC/Swing container that can be used to overlap the components to each other.

JList This class used to create a list where you select the one or more than objects.

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

JMenuBar It used to create a new menu bar where the JMenu objects are added.

JMenuItem This class used to create new menu items in the mebus. 

JOptionPane It used to create some different types of dialog box like: message dialog box, error dialog box etc.

JPanel It extends the JComponent and used to create a new panel.

JPassworkField It provides the single line text editing. Here, don't available the original characters but view type indication characters are available.

JPopupMenu This class used to create a popup menu. It provides small window where the various types of choices are

Page 10: Java Swing

available.JPopupMenu.Separator Here the popup menu and the

separator are available.JProgressBar It shows the integer types values in

percent within a bounded range to determine the working process.

JRadioButton It implements the radio button and shows the state of an item selected or deselected.

JRadioButtonMenuItem It extends the JMenuItem and implements the radio button menu item

JRootPane This class provides the component behind the scenes by JFrame, JWindow, JDialog etc. for providing the task-orientation and functionality.

JScrollBar This class used to create a scroll bar. It provides the view content area where you show the content to scroll this. 

JScrollPane It provides the scrollable view components.

JSeparator This class use the separator among the components.

JSlider This class provides a control to represent a numeric value by dragging the slider.

JSplitPane This class used to divides the two components graphically like: top and button, left and right.

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

JTable It provides the user interface component and represents the two dimensional data.

Page 11: Java Swing

JTextArea It provides the multi line plain text area.

JTextField It provides the facility to editing the text in a single line.

JTextPane This class provides the component like JTexArea for multiple lines text with more capabalities.

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

Page 12: Java Swing

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 monitor the progress of reading input from the input stream. It cleanups all the rights when the stream is closed.

RepaintManager This class manage and override the repaint requests.

ScrollPaneLayout It implements the LayoutManager and manage the components like: scroll bar, row header, column header etc.

ScrollPaneLayout.UIResource It extends the ScrollPaneLayout and implements the UIResource.

SizeRequirements It calculates the size and positions of components.

SizeSequence It represents the order list of size and it's positions.

SwingUtilities This class has utilities methods for swing.

Timer Actions perform the predefined rate.ToolTipManager It manages the all tool tips.UIDefaults It extends the Hashtable and you

set/get the value with the help of UIManager.

UIDefaults.LazyInputMap 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).

Page 13: Java Swing

UIDefaults.ProxyLazyValue This class is used to create a lazy value which is used to delay loading of the class to create instance for that.

UIManager This class has track of the current look and feel details.

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

UnsupportedLookAndFeelExceptionThis exception occurred when the look 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:

Page 14: Java Swing

1. create JFrame object2. Get content pane3. 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) Removes the specified component from the frame.

void remove (Component c) Removes the specified component from the frame.

void setDefaultCloseOperation

Sets the action taken when the user closes the frame. Always specify JFrame.EXIT ON CLOSE.

void setIconImage (Icon image)

Sets the icon displayed when the frame is minimized.

void setLayout(LayoutManager layout)

Sets the layout manager used to control how components are

Page 15: Java Swing

arranged when the frame is displayed. The default is the BorderLayout manager.

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.

void setLocationRelativeTo (Component c)

Centers the frame on-screen 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).

void setSize (int width, int height)

Sets the size of the frame to the specified width and 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

frameSteps:

1. Create JFrame object2. Create JPanel object3. Add all component to the JPanel object by using add()

method4. An intermediate JPanel object is made part of content

pane using setContentPane() method of JFrame classExample:

JFrame o=new JFrame();JPanel pnl=new JPanel();pnl.add(<Somecomponent>);o.setContentPane(pnl);

Page 16: Java Swing

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.

Page 17: Java Swing

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(<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()

Set or get the applet's content pane. The content pane contains the applet's visible GUI components and should be opaque.

JRootPane createRootPane() void setRootPane(JRootPane) JRootPane getRootPane()

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.

void setJMenuBar(JMenuBar) JMenuBar getJMenuBar()

Set or get the applet's menu bar to manage a set of menus for the

Page 18: Java Swing

frame.

void setGlassPane(Component) Component getGlassPane()

Set or get the applet's glass pane. You can use the glass pane to intercept mouse events.

void setLayeredPane(JLayeredPane) JLayeredPane getLayeredPane()

Set or get the applet's layered pane. You can use the frame's layered pane to put components 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 objectThe 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

Page 19: Java Swing

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");

Page 20: Java Swing

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(); } }