Sei sulla pagina 1di 44

A Tour of SWING

Prepared by:- Fahad Kharadi


What is Swing

 Present in all modern Java implementations


(since 1.2)
 Swing is a set of classes that provides more
powerful and flexible components.
 Gives a choice of “look and feel” packages.
 Much easier to build an attractive GUI.
 import javax.swing.*;
import javax.swing.event.*;
Swing vs. AWT
 Swing is built “on top of” AWT, so you need to import
AWT and use a few things from it
 Swing is bigger and slower
 Swing is more flexible and better looking
 Swing and AWT are incompatible--you can use either,
but you can’t mix them
 Actually, you can, but it’s tricky and not worth doing
 Basic controls are practically the same in both
 AWT: Button b = new Button ("OK");
 Swing: JButton b = new JButton("OK");
 Swing gives far more options for everything (buttons
with pictures on them, etc.)
Applet 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).
Containers and Components
 A GUI is built by putting components into containers
 The job of a Container is to hold and display Components

 Some frequently used types (subclasses) of Component are


JButton, JCheckbox, JLabel, JTextField, and JTextArea

 A Container is also a Component


 This allows Containers to be nested
 Important Container classes are JFrame, JApplet, and JPanel
 JFrame and JApplet both contain other containers; use
getContentPane() to get to the container you want
 You typically create and use JPanels directly
Starting with a Container
 First, import some packages:
 import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
 Second, extend a Container type:
 For an application, extend JFrame
 public class MyClass extends JFrame { ... }
 For an applet, extend JApplet
 public class MyApplet extends JApplet { ... }
 Neither of these returns a Container that you use
directly; instead,
 Both JFrame and JApplet have a getContentPane()
method that returns a Container you can use:
 getContentPane( )
A JApplet is a Panel is a Container

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
Example: A "Life" applet

Container (Applet)

Containers (Panels)

Component (Canvas)

Components (Buttons)

Components (TextFields)

Components (Labels)
Some types of components
Button Checkbox
Label
Scrollbar

Choice
TextArea
TextField List

Button

Checkbox
CheckboxGroup
Swing Component Classes
CLASS DESCRIPTION
AbstractButton Abstract superclass for Swing
buttons.
ButtonGroup Encapsulates a mutually exclusive
set 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.
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
Creating components

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


JButton but = new JButton ("Click me!");
JCheckBox toggle = new JCheckBox ("toggle");
JTextField txt =
new JextField ("Initial text.", 20);
JScrollbar scrolly = new JScrollbar
(JScrollbar.HORIZONTAL, initialValue,
bubbleSize, minValue, maxValue);
Adding components to the
Applet
class MyApplet extends JApplet {
public void init () {
getContentPane().add(lab);
// or this.getContentPane().add(lab);
getContentPane().add(but);
getContentPane().add(toggle);
getContentPane().add(txt);
getContentPane().add(scrolly);
...}
Creating a JFrame
 When you create an JApplet,
 The size of the applet is determined by the HTML
page
 The browser makes the applet visible
 When you write a GUI for an application,
you need to do these things yourself
 public class MyApplication extends JFrame {

void createMyGUI() {
... add components ...
pack(); // compute the size and lay it out
setVisible(true); // make the JFrame visible
}
}
Components Tour
Icons

 ImageIcon(Stringfilename)
 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, y on the graphics context g.
Additional information about the paint operation can be
provided in comp.
Labels

 JLabel(Icon i) LEFT
RIGHT
 JLabel(String s) CENTER
 JLabel(String s, Icon i, int align).
 Method associated with icon & label.
Icon getIcon( )
String getText( )
void setIcon(Icon i)
void setText(String s)
Example
public class JLabelDemo extends JApplet {
public void init() {
// Get content pane
Container contentPane = getContentPane();
// Create an icon
ImageIcon ii = new ImageIcon("france.gif");
// Create a label
JLabel jl = new JLabel("France", ii,
JLabel.CENTER);
// Add label to the content pane
contentPane.add(jl);
}
}
TextFields & TextAreas

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

 JTextArea(int rows, int cols)


 JTextArea(String s, int rows, int cols)
Example

public class JTextFieldDemo extends JApplet {


JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add text field to content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
}
Button

JButton() Creates a button with no text or icon

JButton(Icon icon) Creates a button with an icon

JButton(String text) Creates a button with text

JButton(String text, Creates a button with initial text and an


Icon icon) icon

setFont(Font font) Specifies Font (Type, Style, Size)


Inherited from JComponent
setBackground(Color Sets background color Inherited from
color) JComponent
 String getText( )
 void setText(String s)
 void setDisabledIcon(Icon di)
 void setPressedIcon(Icon pi)
 void setSelectedIcon(Icon si)
 void setRolloverIcon(Icon ri)
CheckBox
 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);
RadioButton

 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, boolean
state)
Combo Boxes

 JComboBox( )
 Method:-
addItem( itemname in)
Lists

 JList()
 JList(Object[])
 Method:-
setListData()
setVisibleRowCount(int c)
getSelectedValues()
Example
public class Subscriptions extends JFrame {
String[] subs = { "aWT","java","advaced java","software engg.","multimedia
tech.","management","MIS","Operating sys.","LINUX","BYE HAPPY TO READ" };
JList subList = new JList(subs);
public Subscriptions() {
super("Subscriptions");
setSize(150, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel subLabel = new Jlabel(subs);
panel.add(subLabel);
subList.setVisibleRowCount(5);
JScrollPane scroller = new JScrollPane(subLabel);
panel.add(scroller);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
Subscriptions app = new Subscriptions(); } }
Output
Tabbed Panes

 Steps to create a Tabbed Pane:-


1. Create a JTabbedPane object.
2. Call addTab(String str, Component
comp) to add a tab to the pane.
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane o
the applet.
Example

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:-
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);
}
}
STEP 3:- i.e Repeating STEP 2
class ColorsPanel extends class FlavorsPanel
JPanel { extends JPanel {
public ColorsPanel() { public FlavorsPanel() {
JCheckBox cb1 = new JComboBox jcb = new
JCheckBox("Red"); JComboBox();
add(cb1); jcb.addItem("Vanilla");
JCheckBox cb2 = new jcb.addItem("Chocolate");
JCheckBox("Green");
jcb.addItem("Strawberry")
add(cb2); ;
JCheckBox cb3 = new add(jcb);
JCheckBox("Blue");
add(cb3); }
} }
}
Output
ScrollPanes

 JScrollPane(Component comp)
 JScrollPane(int vsb, int hsb)
 JScrollPane(Component comp, int vsb, int
hsb)
VERTICAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_AS_NEEDE
D
VERTICAL_SCROLLBAR_NEVER

HORIZONTAL_SCROLLBAR_ALWAYS
HORIZONTALL_SCROLLBAR_AS_NEEDED
HORIZONTAL_SCROLLBAR_NEVER
ScrollPaneConstants
Example
public class JScrollPaneDemo // Add panel to a scroll pane
extends JApplet { int v =
public void init() {
ScrollPaneConstants.VERTICA
// Get content pane L_SCROLLBAR_AS_NEEDED;
Container contentPane =
getContentPane(); int h =
ScrollPaneConstants.HORIZ
contentPane.setLayout(new ONTAL_SCROLLBAR_AS_NEE
BorderLayout());
DED;
// Add 400 buttons to a panel
JPanel jp = new JPanel();
JScrollPane jsp = new
JScrollPane(jp, v, h);
jp.setLayout(new GridLayout(20,
20)); // Add scroll pane to the
int b = 0; content pane
for(int i = 0; i < 20; i++) { contentPane.add(jsp,
for(int j = 0; j < 20; j++) {
BorderLayout.CENTER);
jp.add(new JButton("Button " + }
b)); }
++b;
}}
Output
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 content
pane of the applet.
Example
public class JTableDemo extends JApplet { // Create the table
public void init() { JTable table = new JTable(data,
// Get content pane colHeads);
Container contentPane = getContentPane();
// Add tree to a scroll pane
// Set layout manager
contentPane.setLayout(new BorderLayout()); int v =
// Initialize column headings ScrollPaneConstants.VERTICAL_SC
final String[] colHeads = { "Name", "Phone",
ROLLBAR_AS_NEEDED;
"Fax" }; int h =
// Initialize data ScrollPaneConstants.HORIZONTAL
final Object[][] data = { _SCROLLBAR_AS_NEEDED;
{ "Gail", "4567", "8675" }, JScrollPane jsp = new
{ "Ken", "7566", "5555" }, JScrollPane(table, v, h);
{ "Viviane", "5634", "5887" }, // Add scroll pane to the content pane
{ "Melanie", "7345", "9222" }, contentPane.add(jsp,
{ "Anne", "1237", "3333" }, BorderLayout.CENTER);
{ "John", "5656", "3144" },
{ "Matt", "5672", "2176" },
}
{ "Claire", "6741", "4244" }, }
{ "Erwin", "9023", "5159" },
{ "Ellen", "1134", "5332" },
{ "Jennifer", "5689", "1212" },
{ "Ed", "9030", "1313" },
{ "Helen", "6751", "1415" }
};
Flowlayout
Output Borderlayout
Tree
 Tree is a heirarchical format .
 Which ca either Expand or Collapse
 JTree jtr=new JTree(TreeNode tn);
 To create TreeNode
 DefaultMutableTreeNodedmtn=new
DefaultMutableTreeNode(String s);
 Now to AddListener
Void addTreeExpansionListener(TreeExpansionListener tel)
Void addRemoveExpansionListener(TreeExpansionListener tel
 Method associated with the tree
listener is
Void TreeCollapsed(TreeExpansionEvent
tev)
Void TreeExpand(TreeExpansionEvent
When subtree
When subtree
is HIDDEN
tev) become
vissible
Example
DefaultMutableTreeNode a1=new
public class Stree extends JApplet DefaultMutableTreeNode("SRILANKA");
{ root.add(a1);
public void init() DefaultMutableTreeNode a11=new
{ DefaultMutableTreeNode("REYLORD");
Container c=getContentPane(); a1.add(a11);
c.setLayout(new BorderLayout()); DefaultMutableTreeNode a2=new
DefaultMutableTreeNode root=new DefaultMutableTreeNode("PAKISTAN");
DefaultMutableTreeNode("WORLD"); root.add(a2);
DefaultMutableTreeNode a=new DefaultMutableTreeNode a3=new
DefaultMutableTreeNode("INDIA"); DefaultMutableTreeNode("FLIENG");
root.add(a); a2.add(a3);
DefaultMutableTreeNode b=new JTree jt= new JTree(root);
DefaultMutableTreeNode("MUMBAI"); int v=
a.add(b); ScrollPaneConstants.VERTICAL_SCROLLBAR
DefaultMutableTreeNode b11=new _AS_NEEDED;
DefaultMutableTreeNode("WARDEN RD"); int h=
b.add(b11); ScrollPaneConstants.HORIZONTAL_SCROLL
DefaultMutableTreeNode b12=new BAR_AS_NEEDED;
DefaultMutableTreeNode("BYCULLA"); JScrollPane jsp=new JScrollPane(jt,v,h);
b.add(b12); c.add(jsp,BorderLayout.CENTER);
DefaultMutableTreeNode b1=new }
DefaultMutableTreeNode("DELHI"); }
a.add(b1);
DefaultMutableTreeNode b3=new
DefaultMutableTreeNode("KARNATAKA");
a.add(b3);
Output
OUT OF SYLLABUS

 JSlider:
 JToolBar:
 JProgressBar:
 Different
types of JDialogBoxes:
Etc………..

Potrebbero piacerti anche