Swing
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Swing

on

  • 1,375 views

 

Statistics

Views

Total Views
1,375
Views on SlideShare
1,375
Embed Views
0

Actions

Likes
0
Downloads
66
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Swing Document Transcript

  • 1. 3 Cube Computer Institute Website: www.3cci.in 1. Introduction to SwingSwing:Swing is a set of classes that provides more powerful and flexible components than are possible with theAWT. In addition to the familiar components, such as buttons, check boxes, and labels, Swing suppliesseveral exciting additions, including tabbed panes, scroll panes, trees, and tables.Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, theyare written entirely in Java and, therefore, are platform-independent. The term lightweight is used to describesuch elements.The Swing-related classes are contained in javax.swing and its subpackages, such as javax.swing.JTree.Difference between Awt and Swing: Awt SwingNative component. Pure Java component.Components are heavy weight. Components are light weight.Native look and feel. Pure java component.Does not have complex component. It has additional components like JTree, JTable, JProgressBar, and JSlider ect.Applet can not have menu. JApplet can contain menu.Components like Button can not have images. Components like JButton can have images.List has scrollbar. JList doesn’t support scrolling but this can be done using ScrollPane.Components can be added directly on the Window While adding component to window or Frame, theyor Frame. have to be added on its ContentPane.Does not have SplitPane or TabbedPane. Has SplitPane or TabbedPane.Do not have MDI window. MDI can be achieved using JInternalFrame Object.Menu item can not have images or radio button or Menu item can have images or radio button or checkcheck boxes. boxes.JApplet:Fundamental to Swing is the JApplet class, which extends Applet. JApplet is rich with functionality that isnot found in Applet. For example, JApplet supports various “panes,” such as the content pane, the glasspane, and the root pane.Unlike Applet BorderLayout is default layout of JApplet.When adding a component to an instance of JApplet, do not invoke the add ( ) method of the applet. Instead,call add ( ) for the content pane of the JApplet object. The content pane can be obtained via the methodshown here:Container getContentPane ( )Hierarchy: java.lang.Object java.awt.Component java.awt.Container java.awt.Panel java.applet.Applet javax.swing.JApplet Reference: The Complete Reference, Java Doc
  • 2. 3 Cube Computer Institute Website: www.3cci.inExample:Import java.awt.*;Import javax.swing.*;//<Applet code=MyClass width=300 height=300></Applet>public class MyClass extends JApplet{ JLabel l1 = new JLabel (“First Label”); public void init( ) { Container con = getContentPane ( ); con.setLayout (new FlowLayout ( )); con.add (l1); }}Difference between Applet and JApplet: Applet JAppletApplet doesn’t have rich functionality as JApplet is with rich functionality.JApplet.We add component to Applet. We add component to ContentPane.We can not add MenuBar We can add JMenuBar to JApplet.LayoutManager is set to Applet. LayoutManager is set to JApplet.Default Layout is FlowLayout. Default Layout is BorderLayout.Container:The Container class is a subclass of the Component class that is used to define components that have thecapability to contain other components. It provides methods for adding, retrieving, displaying, counting, andremoving the components that it contains. The Container class also provides methods for working withlayouts. The layout classes control the layout of components within a container.Hierarchy: java.lang.Object java.awt.Component java.awt.ContainerThe methods of the class Container are:Component add (Component c) Adds the component to the end of this containervoid setLayout (LayoutManager m) Re-Sets the Container’s LayoutManagervoid removeAll () Removes all ComponentsExample:You can give above example. Reference: The Complete Reference, Java Doc
  • 3. 3 Cube Computer Institute Website: www.3cci.in JWindow: JWindow class is similar to the JFrame class. It uses a JRootPane for component management andimplements the RootPaneContainer.Basically it is top level window with no andorment s.JWindow class addsno additional event handling capabilities beyond thoes of the JFrame and Window Classes.Hierarchy: java.lang.Object java.awt.Component java.awt.Container java.awt.Window java.swing.JWindowConstructor:JWindow() Creates a window with no specified owner.JWindow(Frame owner) Creates a window with the specified owner frame.JWindow(GraphicsConfiguration gc) Creates a window with the specified GraphicsConfiguration of a screen device.Methods:setSize(int height, int width);setLocation(int x, int y); setVisible(boolean state);Example:import javax.swing.*; public class TopLevelWindows { public static void main(String[] args) { JFrame f = new JFrame("The Frame"); f.setSize(300, 300); f.setLocation(100, 100); JWindow w = new JWindow( ); w.setSize(300, 300); w.setLocation(500, 100); f.setVisible(true); w.setVisible(true); } } Reference: The Complete Reference, Java Doc
  • 4. 3 Cube Computer Institute Website: www.3cci.inJFrame:Simply put, if you know how to use the AWT Frame class, then you can use JFrame. JFrame is an extendedversion of Frame only. JFrame exhibits a slight incompatibility when compared to the AWT Frame classbecause it contains only a single child (which is an instance of JRootPane). In order to add any othercomponents to the JFrame instance, they must be added to the root pane.Hierarchy: java.lang.Object java.awt.Component java.awt.Container java.awt.Window java.awt.Frame javax.swing.JFrameConstructor:JFrame() Constructs a new frame that is initially invisible. JFrame(GraphicsConfiguration gc) Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.JFrame(String title) Creates a new, initially invisible Frame with the specified title.JFrame(String title, GraphicsConfiguration gc) Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.Methods: setLayout(LayoutManager manager) setSize(int height, int width); setLocation(int x, int y); setVisible(boolean state);Example:import javax.swing.*; public class JFrameDemo { public static void main(String[] args) { JFrame f = new JFrame("The Frame"); f.setSize(300, 300); f.setLocation(100, 100); f.setVisible(true); } } Reference: The Complete Reference, Java Doc
  • 5. 3 Cube Computer Institute Website: www.3cci.inJPanel:The Swing equivalent of AWT’s Panel class is JPanel. With few exceptions, everything you know about Panelapplies equally to JPanel. JPanel supports all of the AWT layout managers and also the new layouts providedby Swing.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JPanelConstructor:JPanel() Creates a new JPanel with a double buffer and a flow layout.JPanel(LayoutManager layout) Create a new buffered JPanel with the specified layout managerMethods:setLayout(LayoutManager manager)add(Component c)Example:import javax.swing.*; public class JPanelDemo { public static void main(String[] args) { JFrame f = new JFrame("The Frame"); JPanel p = new JPanel(); f.add(p); f.setSize(300, 300); f.setLocation(100, 100); f.setVisible(true); } } Reference: The Complete Reference, Java Doc
  • 6. 3 Cube Computer Institute Website: www.3cci.in1) Icons :In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image. Two of itsconstructors are shown here:Constructors: ImageIcon(String filename) ImageIcon(URL url) The first form uses the image in the file named filename. The second form uses the image in the resource identified by url.Methods: int getIconHeight( ) int getIconWidth( )2) JLabel:Swing labels are instances of the JLabel class, which extends JComponent. It can display text and/or an icon.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JLabelConstructors: JLabel () Creates a JLabel instance with no image and with an empty string for the title. JLabel (Icon image) Creates a JLabel instance with the specified image. JLabel (String text) Creates a JLabel instance with the specified text. JLabel (String text, Icon icon) Creates a JLabel instance with the specified text and icon.Method: Icon getIcon ( ) String getText ( ) void setIcon (Icon i) void setText (String s) Reference: The Complete Reference, Java Doc
  • 7. 3 Cube Computer Institute Website: www.3cci.inExample:import java.awt.*;import javax.swing.*;/*<applet code="JLabelDemo" width=300 height=50></applet>*/public class JLabelDemo extends JApplet {JLabel l1;ImageIcon i1;public void init() {// Get content paneContainer contentPane = getContentPane();contentPane.setLayout(new FlowLayout());// Add Label to content panei1=new ImageIcon(“sunset.jpg”);j1= new JLabel(i1);contentPane.add(j1);}}3) JTextField: The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It provides functionality that is common to Swing text components. One of its subclasses is JTextField, which allows you to edit one line of text.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.text.JTextComponent javax.swing.JTextFieldConstructors: JTextField () Constructs a new TextField. JTextField (int columns) Constructs a new empty TextField with the specified number of columns. JTextField (String text) Constructs a new TextField initialized with the specified text. JTextField (String text, int columns) Constructs a new TextField initialized with the specified text and columns.Method: String getText () Void setText (String s) int getColumns() void setColumns(int cols) Reference: The Complete Reference, Java Doc
  • 8. 3 Cube Computer Institute Website: www.3cci.inExample:import java.awt.*;import javax.swing.*;/*<applet code="JTextFieldDemo" width=300 height=50></applet>*/public class JTextFieldDemo extends JApplet {JTextField jtf;public void init() {// Get content paneContainer contentPane = getContentPane();contentPane.setLayout(new FlowLayout());// Add text field to content panejtf = new JTextField("This is JTextField ",15);contentPane.add(jtf);}}4) JButton:Swing buttons provide features that are not found in the Button class defined by the AWT. For example, youcan associate an icon with a Swing button. Swing buttons are subclasses of the AbstractButton class, whichextends JComponent.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.AbstractButton javax.swing.JButtonConstructors: JButton () Creates a button with no set text or icon. JButton (Icon icon) Creates a button with an icon. JButton (String text) Creates a button with text. JButton (String text, Icon icon) Creates a button with initial text and an icon.Methods: String getText( ) void setText(String s)Example: Reference: The Complete Reference, Java Doc
  • 9. 3 Cube Computer Institute Website: www.3cci.in5) JCheckBox:The JCheckBox class, which provides the functionality of a check box, is a concrete implementation ofAbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state buttons(checked or unchecked).Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.AbstractButton javax.swing.JToggleButton javax.swing.JCheckBoxConstructors:JCheckBox () Creates an initially unselected check box button with no text, no icon.JCheckBox (Icon icon) Creates an initially unselected check box with an icon.JCheckBox (Icon icon, boolean selected) Creates a check box with an icon and specifies whether or not it is initially selected. JCheckBox (String text) Creates an initially unselected check box with text.JCheckBox (String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected.JCheckBox (String text, Icon icon) Creates an initially unselected check box with the specified text and icon. JCheckBox (String text, Icon icon, boolean selected) Creates a check box with text and icon, and specifies whether or not it is initially selected.Methods: void setSelected(boolean state) void setLabel(String label) void setIcon(Icon icon) boolean isSelected()Example: Reference: The Complete Reference, Java Doc
  • 10. 3 Cube Computer Institute Website: www.3cci.in6) JRadioButton:Radio buttons are supported by the JRadioButton class, which is a concrete implementation ofAbstractButton. Its immediate superclass is JToggleButton, which provides support for two-state buttons.Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at anytime. The ButtonGroup class is instantiated to create a button group. Its default constructor is invoked forthis purpose. Elements are then added to the button group via the following method: void add(AbstractButton ab)Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.AbstractButton javax.swing.JToggleButton javax.swing.JRadioButtonConstructors:JRadioButton () Creates an initially unselected radio button with no set text. JRadioButton (Icon icon) Creates an initially unselected radio button with the specified image but no text. JRadioButton (Icon icon, boolean selected) Creates a radio button with the specified image and selection state, but no text. JRadioButton (String text) Creates an unselected radio button with the specified text. JRadioButton (String text, boolean selected) Creates a radio button with the specified text and selection state.JRadioButton (String text, Icon icon) Creates a radio button that has the specified text and image, and that is initially unselected. JRadioButton (String text, Icon icon, boolean selected) Creates a radio button that has the specified text, image, and selection state.Methods: void setSelected(boolean state) void setLabel(String label) void setIcon(Icon icon) boolean isSelected()Example: Reference: The Complete Reference, Java Doc
  • 11. 3 Cube Computer Institute Website: www.3cci.in7) JComboBox:Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBoxclass, which extends JComponent. A combo box normally displays one entry. However, it can also display adrop-down list that allows a user to select a different entry. You can also type your selection into the textfield.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JComboBoxConstructors:JComboBox () Creates a JComboBox with a default data model.JComboBox (Object [] items) Creates a JComboBox that contains the elements in the specified array.JComboBox (Vector items) Creates a JComboBox that contains the elements in the specified Vector.Methods: Object getItemAt (int index) int getItemCount () int getSelectedIndex () Object getSelectedItem () addItem (Object anObject)Example: Reference: The Complete Reference, Java Doc
  • 12. 3 Cube Computer Institute Website: www.3cci.in8) JTabbedPane:A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title, whena user selects the folder, its contents become visible. Only one of the folders may be selected at a time.Tabbed panes are commonly used for setting configuration options. Tabbed panes are encapsulated by theJTabbedPane class, which extends JComponent.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JTabbedPaneConstructors:JTabbedPane () Creates an empty TabbedPane with a default tab placement of JTabbedPane.TOP.JTabbedPane (int tabPlacement) Creates an empty TabbedPane with the specified tab placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, or JTabbedPane.RIGHT.JTabbedPane (int tabPlacement, int tabLayoutPolicy) Creates an empty TabbedPane with the specified tab placement and tab layout policy.Methods: void addTab(String title, Component component) void addTab(String title, Icon icon, Component component) void addTab(String title, Icon icon, Component component, String tip)Example: Reference: The Complete Reference, Java Doc
  • 13. 3 Cube Computer Institute Website: www.3cci.in9) JScrollPane:A scroll pane is a component that presents a rectangular area in which a component may be viewed.Horizontal and/or vertical scroll bars may be provided if necessary. Scroll panes are implemented in Swingby the JScrollPane class, which extends JComponent.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JScrollPaneConstructors:JScrollPane () Creates an empty (no viewport view) JScrollPane where both horizontal and vertical scrollbars appearwhen needed.JScrollPane (int vsbPolicy, int hsbPolicy) Creates an empty (no viewport view) JScrollPane with specified scrollbar policies.Methods:JScrollBar getVerticalScrollBar ()void setVerticalScrollBar (JScrollBar bar)JScrollBar getHorizontalScrollBar ()void setHorizontalScrollBar (JScrollBar bar) Reference: The Complete Reference, Java Doc
  • 14. 3 Cube Computer Institute Website: www.3cci.in10) JTree:A tree is a component that presents a hierarchical view of data. A user has the ability to expand or collapseindividual subtrees in this display. Trees are implemented in Swing by the JTree class, which extendsJComponent.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JTreeConstructors:JTree () Returns a JTree with a sample model.JTree (TreeNode root) Returns a JTree with the specified TreeNode as its root, which displays the root node.Methods:int getRowCount()int getRowForLocation(int x, int y)TreePath getPathForLocation (int x int y)Example: Reference: The Complete Reference, Java Doc
  • 15. 3 Cube Computer Institute Website: www.3cci.in11) JTable:A table is a component that displays rows and columns of data. You can drag the cursor on columnboundaries to resize columns. You can also drag a column to a new position. Tables are implemented by theJTable class, which extends JComponent.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JTableConstrustors:JTable () Constructs a default JTable that is initialized with a default data model, a default column model, anda default selection model.JTable (int numRows, int numColumns) Constructs a JTable with numRows and numColumns of empty cells using DefaultTableModel. JTable(Object [][] rowData, Object[] columnNames) Constructs a JTable to display the values in the two dimensional array, rowData, with column names,columnNames.JTable (Vector rowData, Vector columnNames) Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names,columnNames. Reference: The Complete Reference, Java Doc
  • 16. 3 Cube Computer Institute Website: www.3cci.inExample:import java.awt.*;import javax.swing.*;/*<applet code="JTableDemo" width=400 height=200></applet>*/public class JTableDemo extends JApplet {public void init() {// Get content paneContainer contentPane = getContentPane();// Set layout managercontentPane.setLayout(new BorderLayout());// Initialize column headingsString[] colHeads = { "Name", "Phone", "Fax" };// Initialize dataObject[][] data = {{ "Gail", "4567", "8675" },{ "Ken", "7566", "5555" },{ "Viviane", "5634", "5887" },{ "Melanie", "7345", "9222" },{ "Anne", "1237", "3333" },{ "John", "5656", "3144" },{ "Matt", "5672", "2176" },{ "Claire", "6741", "4244" },{ "Erwin", "9023", "5159" },{ "Ellen", "1134", "5332" },{ "Jennifer", "5689", "1212" },{ "Ed", "9030", "1313" },{ "Helen", "6751", "1415" }};// Create the tableJTable table = new JTable (data, colHeads);// Add table to a scroll paneint v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;JScrollPane jsp = new JScrollPane (table, v, h);// Add scroll pane to the content panecontentPane.add (jsp, BorderLayout.CENTER);} } Reference: The Complete Reference, Java Doc
  • 17. 3 Cube Computer Institute Website: www.3cci.in12) JList A list box is simply a user interface control containing a collection of similar items from which the user can make one or more selections. This is the premise behind the AWT List control, which presents a Java component equivalent to list box objects found in all other graphics interfaces. Lists are implemented by the JList class, which extends JComponent.Hierarchy: java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JListConstructor:JList() Constructs a JList with an empty model.JList(ListModel dataModel) Constructs a JList that displays the elements in the specified, non-null model.JList(Object[] listData) Constructs a JList that displays the elements in the specified array.JList(Vector listData) Constructs a JList that displays the elements in the specified Vector.Methods: Reference: The Complete Reference, Java Doc
  • 18. 3 Cube Computer Institute Website: www.3cci.inExample:import java.awt.*;import java.awt.event.*;import javax.swing.*;class ListDemo extends JFrame{// Instance attributes used in this exampleJPanel topPanel;JList listbox;// Constructor of main framepublic ListDemo (){// Create a panel to hold all other componentstopPanel = new JPanel();topPanel.setLayout( new BorderLayout() );getContentPane().add( topPanel );// Create some items to add to the listString listData[] ={"Item 1","Item 2","Item 3","Item 4"};// Create a new list box controllistbox = new JList( listData );topPanel.add( listbox, BorderLayout.CENTER );setSize( 300, 100 );setVisible( true );}public static void main( String args[] ){// Create an instance of the test applicationListDemo ld = new ListDemo ();}} Reference: The Complete Reference, Java Doc