Top Banner

of 44

A Tour of SWING

Apr 08, 2018

Download

Documents

Haroon Kotadiya
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/7/2019 A Tour of SWING

    1/44

    A Tour of SWINGA Tour of SWING

    Prepared by:- Fahad Kharadi

  • 8/7/2019 A Tour of SWING

    2/44

    What is SwingWhat is Swing

    Present in all modern Java implementationsPresent in all modern Java implementations(since 1.2)(since 1.2)

    Swing is a set of classes that provides more

    powerful and flexible components.Gives a choice of look and feel packages.Gives a choice of look and feel packages.Much easier to build an attractive GUI.Much easier to build an attractive GUI. import javax.swing.*;import javax.swing.*;

    import javax.swing.event.*;import javax.swing.event.*;

  • 8/7/2019 A Tour of SWING

    3/44

    Swing vs. AWTSwing vs. AWT

    Swing is built on top of AWT, so you need to importSwing is built on top of AWT, so you need to importAWT and use a few things from itAWT and use a few things from it

    Swing is bigger and slowerSwing is bigger and slower

    Swing is more flexible and better lookingSwing is more flexible and better looking Swing and AWT areSwing and AWT are incompatibleincompatible--you can use either,--you can use either,

    but you cant mix thembut you cant mix them Actually, you can, but its tricky and not worth doingActually, you can, but its tricky and not worth doing

    Basic controls are practically the same in bothBasic controls are practically the same in both

    AWT:AWT: Button b = new Button ("OK");Button b = new Button ("OK"); Swing:Swing: JButton b = new JButton("OK");JButton b = new JButton("OK");

    Swing givesSwing gives far morefar more options for everything (buttonsoptions for everything (buttonswith pictures on them, etc.)with pictures on them, etc.)

  • 8/7/2019 A Tour of SWING

    4/44

    Applet vs. ApplicationApplet vs. Application

    Using Swing it is possible to create two different

    types of GUI programs Standalone applications

    Programs that are started from the command line Code resides on the machine on which they are run

    Applets Programs run inside a web browser

    Code is downloaded from a web server

    JVM is contained inside the web browser

    For security purposes Applets are normally prevented from

    doing certain things (for example opening files).

  • 8/7/2019 A Tour of SWING

    5/44

    Containerontainers ands and ComponentComponentss

    A GUI is built by puttingA GUI is built by putting componentscomponents intointo containerscontainers The job of aThe job of a ContainerContainer is to hold and displayis to hold and display ComponentComponentss

    Some frequently used types (subclasses) ofSome frequently used types (subclasses) ofComponentComponent areare

    JButtonJButton,, JCheckboxJCheckbox,, JLabelJLabel,, JTextFieldJTextField, and, andJTextAreaJTextArea

    AA ContainerContainer is also ais also a ComponentComponent This allows Containers to be nestedThis allows Containers to be nested

    ImportantImportant ContainerContainer classes areclasses are JFrameJFrame,, JAppletJApplet, and, and JPanelJPanel JFrameJFrame andand JAppletJApplet both contain other containers; useboth contain other containers; use

    getContentPane()getContentPane() to get to the container you wantto get to the container you want You typically create and useYou typically create and use JPanelJPanels directlys directly

  • 8/7/2019 A Tour of SWING

    6/44

    Starting with aStarting with a ContainerContainer

    First, import some packages:First, import some packages: import javax.swing.*;import javax.swing.*;

    import javax.swing.event.*;import javax.swing.event.*;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;

    Second, extend a Container type:Second, extend a Container type: For an application, extendFor an application, extend JFrameJFrame

    public class MyClass extends JFrame { ... }public class MyClass extends JFrame { ... } For an applet, extendFor an applet, extend JAppletJApplet

    public class MyApplet extends JApplet { ... }public class MyApplet extends JApplet { ... }

    Neither of these returns a Container that you useNeither of these returns a Container that you usedirectly; instead,directly; instead,

    BothBoth JFrameJFrame andand JAppletJApplet have ahave a getContentPane()getContentPane()method that returns amethod that returns a ContainerContainer you can use:you can use: getContentPane( )getContentPane( )

  • 8/7/2019 A Tour of SWING

    7/44

    JAppletJApplet is ais a PanelPanel is ais a ContainerContainer

    java.lang.Object|java.awt.Component

    |java.awt.Container

    |java.awt.Panel

    |java.applet.Applet

    |javax.swing.JApplet

    so you can display things in an

  • 8/7/2019 A Tour of SWING

    8/44

    Example: A "Life" appletExample: A "Life" applet

    Container (Applet)

    Containers (Panels)

    Component (Canvas)

    Components (Buttons)

    Components (Labels)

    Components (TextFields)

  • 8/7/2019 A Tour of SWING

    9/44

    ome types of componentsome types of components

    Label Button

    Button

    Checkbox

    Choice

    ListTextField

    CheckboxGroupCheckbox

    Scrollbar

    TextArea

  • 8/7/2019 A Tour of SWING

    10/44

    wing Component Classeswing Component Classes

    CLASSCLASS DESCRIPTIONDESCRIPTION

    AbstractButton Abstract superclass for Swingbuttons.

    ButtonGroup Encapsulates a mutually exclusiveset of buttons.

    ImageIcon Encapsulates an icon

    JApplet The Swing version of Applet.JButton The Swing push button class

    JCheckBox The Swing check box class.

    JLabel The Swing version of a label.

  • 8/7/2019 A Tour of SWING

    11/44

    JComboBox Encapsulates a combo box

    JRadioButton The Swing version of a radio

    button.JScrollPane Encapsulates a scrollable window.

    JTabbedPane Encapsulates a tabbed window.JTable Encapsulates a table-based

    control.

    JTextField The Swing version of a text field

    -

  • 8/7/2019 A Tour of SWING

    12/44

    Creating componentsCreating components

    JLabel lab = new JLabel ("Hi, Dave!");JLabel lab = new JLabel ("Hi, Dave!");

    JButton but = new JButton ("Click me!");JButton but = new JButton ("Click me!");

    JCheckBox toggle = new JCheckBox ("toggle");JCheckBox toggle = new JCheckBox ("toggle"); JTextField txt =JTextField txt =new JextField ("Initial text.", 20);new JextField ("Initial text.", 20);

    JScrollbar scrolly = new JScrollbarJScrollbar scrolly = new JScrollbar

    (JScrollbar.HORIZONTAL, initialValue,(JScrollbar.HORIZONTAL, initialValue,bubbleSize, minValue, maxValue);bubbleSize, minValue, maxValue);

  • 8/7/2019 A Tour of SWING

    13/44

    Adding components to theAdding components to theAppletApplet

    class MyApplet extends JApplet {class MyApplet extends JApplet {

    public void init () {public void init () {

    getContentPane().add(lab);getContentPane().add(lab);

    // or// or this.this.getContentPane().add(lab);getContentPane().add(lab);

    getContentPane().add(but);getContentPane().add(but);

    getContentPane().add(toggle);getContentPane().add(toggle);

    getContentPane().add(txt);getContentPane().add(txt); getContentPane().add(scrolly);getContentPane().add(scrolly);

    ...}...}

  • 8/7/2019 A Tour of SWING

    14/44

    Creating aCreating a JFrameJFrame

    When you create anWhen you create an JAppletJApplet,, The size of the applet is determined by the HTMLThe size of the applet is determined by the HTML

    pagepage The browser makes the applet visibleThe browser makes the applet visible

    When you write a GUI for anWhen you write a GUI for an application,application,you need to do these things yourselfyou need to do these things yourself public class MyApplication extends JFrame {public class MyApplication extends JFrame {

    void createMyGUI() {void createMyGUI() { ... add components ...... add components ... pack(); // compute the size and lay it outpack(); // compute the size and lay it out setVisible(true); // make the JFrame visiblesetVisible(true); // make the JFrame visible

    }}}}

  • 8/7/2019 A Tour of SWING

    15/44

    Components TourComponents Tour

  • 8/7/2019 A Tour of SWING

    16/44

    IconsIcons

    ImageIcon(String filename) ImageIcon(URL url)Methods: int getIconHeight( )

    Returns the height of the icon in pixels.

    int getIconWidth( )Returns the width of the icon in pixels.

    void paintIcon(Component comp,Graphics g,int x,int y)Paints the icon at position x, yon the graphics context g.

    Additional information about the paint operation can beprovided in comp.

  • 8/7/2019 A Tour of SWING

    17/44

  • 8/7/2019 A Tour of SWING

    18/44

    ExampleExample

    public class JLabelDemo extends JApplet {public void init() {// Get content paneContainer contentPane = getContentPane();// Create an iconImageIcon ii = new ImageIcon("france.gif");// Create a labelJLabel jl = new JLabel("France", ii,

    JLabel.CENTER);// Add label to the content panecontentPane.add(jl);}}

  • 8/7/2019 A Tour of SWING

    19/44

    JTextField( )

    JTextField(int cols)

    JTextField(String s, int cols)JTextField(String s)

    JTextArea(int rows, int cols)

    JTextArea(String s, int rows, int cols)

    TextFields & TextAreasTextFields & TextAreas

  • 8/7/2019 A Tour of SWING

    20/44

    ExampleExample

    public class JTextFieldDemo extends JApplet {

    JTextField jtf;

    public void init() {

    // Get content paneContainer contentPane = getContentPane();

    contentPane.setLayout(new FlowLayout());

    // Add text field to content pane

    jtf = new JTextField(15);contentPane.add(jtf);

    }

    }

  • 8/7/2019 A Tour of SWING

    21/44

    ButtonButton

    JButtonJButton()() Creates a button with no text or iconCreates a button with no text or icon

    JButtonJButton(Icon icon)(Icon icon) Creates a button with an iconCreates a button with an icon

    JButtonJButton(String text)(String text) Creates a button with textCreates a button with text

    JButtonJButton(String text,(String text,

    Icon icon)Icon icon)

    Creates a button with initial text and anCreates a button with initial text and an

    iconicon

    setFontsetFont(Font font)(Font font) Specifies Font (Type, Style, Size)Specifies Font (Type, Style, Size)Inherited from JComponentInherited from JComponent

    setBackgroundsetBackground(Color(Colorcolor)color)

    Sets background colorSets background color Inherited fromInherited fromJComponentJComponent

  • 8/7/2019 A Tour of SWING

    22/44

    String getText( )

    void setText(String s)

    void setDisabledIcon(Icon di)void setPressedIcon(Icon pi)

    void setSelectedIcon(Icon si)

    void setRolloverIcon(Icon ri)

  • 8/7/2019 A Tour of SWING

    23/44

    CheckBoxCheckBox

    JCheckBox(Icon i) JCheckBox(Icon i, boolean state) JCheckBox(String s)

    JCheckBox(String s, boolean state) JCheckBox(String s, Icon i) JCheckBox(String s, Icon i, boolean state) Method:-

    void setSelected(boolean state) getItem( ) getText( ) setRolloverIcon(Icon ri); setSelectedIcon(Icon si);

  • 8/7/2019 A Tour of SWING

    24/44

    RadioButtonRadioButton

    JRadioButton(Icon i)

    JRadioButton(Icon i, boolean state)

    JRadioButton(String s)JRadioButton(String s, boolean state)

    JRadioButton(String s, Icon i)

    JRadioButton(String s, Icon i, booleanstate)

  • 8/7/2019 A Tour of SWING

    25/44

    Combo BoxesCombo Boxes

    JComboBox( )

    Method:-

    addItem( itemname in)

  • 8/7/2019 A Tour of SWING

    26/44

    ListsLists

    JList()

    JList(Object[])

    Method:-setListData()

    setVisibleRowCount(int c)

    getSelectedValues()

  • 8/7/2019 A Tour of SWING

    27/44

    ExampleExample

    public class Subscriptions extends JFrame {public class Subscriptions extends JFrame {String[] subs = {String[] subs = { "aWT","java","advaced java","software engg.","multimedia"aWT","java","advaced java","software engg.","multimedia

    tech.","management","MIS","Operating sys.","LINUX","BYE HAPPY TO READ" };tech.","management","MIS","Operating sys.","LINUX","BYE HAPPY TO READ" };

    JList subList = new JList(subsJList subList = new JList(subs););public Subscriptions() {public Subscriptions() {

    super("Subscriptions");super("Subscriptions");

    setSize(150, 300);setSize(150, 300);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();JPanel panel = new JPanel();JLabel subLabel = new Jlabel(subs);JLabel subLabel = new Jlabel(subs);

    panel.add(subLabel);panel.add(subLabel);

    subList.setVisibleRowCount(5);subList.setVisibleRowCount(5);

    JScrollPane scroller = new JScrollPane(subLabel);JScrollPane scroller = new JScrollPane(subLabel);

    panel.add(scroller);panel.add(scroller);add(panel);add(panel);

    setVisible(true);setVisible(true);

    }}

    public static void main(String[] args) {public static void main(String[] args) {

    Subscriptions app = new Subscriptions(); } }Subscriptions app = new Subscriptions(); } }

  • 8/7/2019 A Tour of SWING

    28/44

    OutputOutput

  • 8/7/2019 A Tour of SWING

    29/44

    Tabbed PanesTabbed Panes

    Steps to create a Tabbed Pane:-Steps to create a Tabbed Pane:-

    1. Create a JTabbedPane object.

    2. Call addTab(String str, Componentcomp) to add a tab to the pane.

    3. Repeat step 2 for each tab.

    4. Add the tabbed pane to the content panethe applet.

  • 8/7/2019 A Tour of SWING

    30/44

    ExampleExample

    STEP 1:-public class JTabbedPaneDemo extends

    JApplet {

    public void init() {JTabbedPane jtp = new JTabbedPane();jtp.addTab("Cities", new CitiesPanel());jtp.addTab("Colors", new ColorsPanel());

    jtp.addTab("Flavors", new FlavorsPanel());getContentPane().add(jtp);

    }} STEP

    4:-

  • 8/7/2019 A Tour of SWING

    31/44

    STEP 2:-class CitiesPanel extends JPanel {public CitiesPanel() {

    JButton b1 = new JButton("New York");add(b1);JButton b2 = new JButton("London");add(b2);JButton b3 = new JButton("Hong Kong");

    add(b3);JButton b4 = new JButton("Tokyo");add(b4);

    }}

  • 8/7/2019 A Tour of SWING

    32/44

    class ColorsPanel extendsJPanel {

    public ColorsPanel() {JCheckBox cb1 = new

    JCheckBox("Red");add(cb1);JCheckBox cb2 = new

    JCheckBox("Green");

    add(cb2);JCheckBox cb3 = new

    JCheckBox("Blue");add(cb3);}

    }

    class FlavorsPanelextends JPanel {

    public FlavorsPanel() {JComboBox jcb = new

    JComboBox();jcb.addItem("Vanilla");jcb.addItem("Chocolate");

    jcb.addItem("Strawberry");add(jcb);}}

    STEP 3:- i.e Repeating STEP 2

  • 8/7/2019 A Tour of SWING

    33/44

    OutputOutput

  • 8/7/2019 A Tour of SWING

    34/44

    ScrollPanesScrollPanes

    JScrollPane(Component comp)

    JScrollPane(int vsb, int hsb)

    JScrollPane(Component comp, int vsb, inthsb)VERTICAL_SCROLLBAR_ALWAYS

    VERTICAL_SCROLLBAR_AS_NEEDE

    DVERTICAL_SCROLLBAR_NEVER

    HORIZONTAL_SCROLLBAR_ALWAYSHORIZONTALL_SCROLLBAR_AS_NEEDED

    HORIZONTAL_SCROLLBAR_NEVER

    crollPaneConstants

  • 8/7/2019 A Tour of SWING

    35/44

    ExampleExample

    public class JScrollPaneDemoextends JApplet {

    public void init() {// Get content paneContainer contentPane =

    getContentPane();

    contentPane.setLayout(newBorderLayout());

    // Add 400 buttons to a panelJPanel jp = new JPanel();jp.setLayout(new GridLayout(20,

    20));int b = 0;for(int i = 0; i < 20; i++) {for(int j = 0; j < 20; j++) {jp.add(new JButton("Button " +

    b));++b;}}

    // Add panel to a scroll paneint v =ScrollPaneConstants.VERTICA

    L_SCROLLBAR_AS_NEEDED;int h =

    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

    JScrollPane jsp = newJScrollPane(jp, v, h);

    // Add scroll pane to thecontent pane

    contentPane.add(jsp,BorderLayout.CENTER);

    }}

  • 8/7/2019 A Tour of SWING

    36/44

    OutputOutput

  • 8/7/2019 A Tour of SWING

    37/44

    TableTable

    Steps to create a table:-Steps to create a table:-

    1. Create a JTable object.

    2. Create a JScrollPane object.3. Add the table to the scroll pane.

    4. Add the scroll pane to the contentpane of the applet.

  • 8/7/2019 A Tour of SWING

    38/44

  • 8/7/2019 A Tour of SWING

    39/44

    OutputOutputFlowlayout Borderlayout

  • 8/7/2019 A Tour of SWING

    40/44

    TreeTree

    Tree is a heirarchical format .Tree is a heirarchical format .Which ca either Expand or CollapseWhich ca either Expand or Collapse JTree jtr=new JTree(TreeNode tn);JTree jtr=new JTree(TreeNode tn);

    To create TreeNodeTo create TreeNodeDefaultMutableTreeNode dmtn=newDefaultMutableTreeNode dmtn=new

    DefaultMutableTreeNode(String s);DefaultMutableTreeNode(String s);

    Now to AddListenerNow to AddListenerVoid addTreeExpansionListener(TreeExpansionListener tel)Void addTreeExpansionListener(TreeExpansionListener tel)

    Void addRemoveExpansionListener(TreeExpansionListener teVoid addRemoveExpansionListener(TreeExpansionListener te

  • 8/7/2019 A Tour of SWING

    41/44

    Method associated with the treeMethod associated with the treelistener islistener is

    Void TreeCollapsed(TreeExpansionEventVoid TreeCollapsed(TreeExpansionEventtev)tev)

    Void TreeExpand(TreeExpansionEventVoid TreeExpand(TreeExpansionEventtev)tev)

    When subtreeis HIDDEN

    When subtreebecome

    vissible

  • 8/7/2019 A Tour of SWING

    42/44

  • 8/7/2019 A Tour of SWING

    43/44

  • 8/7/2019 A Tour of SWING

    44/44

    OUT OF SYLLABUSOUT OF SYLLABUS

    JSlider:JSlider:

    JToolBar:JToolBar:

    JProgressBar:JProgressBar:Different types of JDialogBoxes:Different types of JDialogBoxes:

    Etc..Etc..