You are on page 1of 43

Advanced Java Programming

Archana Gopnarayan
Lecturer , Department of Information Technology (NBA Accrediated)
Vidyalankar Polytechnic
Swing
• Swing is a set of classes that provides more powerful and flexible
components than are possible with the AWT.
• In addition to the familiar components, such as buttons, check boxes, and
labels, Swing supplies several exciting additions, including tabbed panes,
scroll panes, trees, and tables. Even familiar components such as buttons
have more capabilities in Swing.
• a button may have both an image and a text string associated with it. Also,
the image can be changed as the state of the button changes.
• Swing Components Are Lightweight
• Swing Supports a Pluggable Look and Feel
Swing Classes
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.
JComboBox Encapsulates a combo box (an combination of a
drop-down list and text field).
JLabel The Swing version of a label.
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.
JTree Encapsulates a tree-based control.
JApplet
• Fundamental to Swing is the JApplet class, which extends Applet. JApplet is rich
with functionality that is not found in Applet.
• 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 method shown here:
getContentPane( )
Icons and Labels
• In Swing, icons are encapsulated by the ImageIcon class, which paints an icon
from an image.
Two of its constructors are shown here:
ImageIcon(String filename)
ImageIcon(URL url)

Methods
int getIconHeight( )
int getIconWidth( )
• Swing labels are instances of the JLabel class, which extends JComponent. It can
display text and/or an icon.
Constructors are shown here:
• JLabel(Icon i)
• JLabel(String s)
• JLabel(String s, Icon i, int align)
The align argument is either LEFT, RIGHT, CENTER, LEADING, or TRAILING.
methods:
• Icon getIcon( )
• String getText( )
• void setIcon(Icon i)
• void setText(String s)
import java.awt.*;
import javax.swing.*;
/*<applet code="JLabelDemo" width=250 height=150>
</applet>*/
public class JLabelDemo extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
ImageIcon ii = new ImageIcon("rose.jpeg");
JLabel jl = new JLabel(ii);
contentPane.add(jl);
}
}
Text Fields
• The Swing text field is encapsulated by the JTextComponent class, which
extends JComponent.
• JTextField, which allows us to edit one line of text.
• constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)

JTextField jt=new JTextField(“IF”,3);


Swing Buttons
Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and
JRadioButton.
•All are subclasses of the AbstractButton class, which extends JComponent.
•AbstractButton contains many methods that allow you to control the behavior of
buttons.
JButton Class
• The JButton class provides the functionality of a push button. JButton allows an
icon, a string, or both to be associated with the push button.
• constructors are
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
JToggleButton
• A useful variation on the push button is called a toggle button.
• A toggle button looks just like a push button, but it acts differently because it has two states:
pushed and released.
• JToggleButton is a superclass for two other Swing components that also represent two-state
controls, JCheckBox and JRadioButton.

• Construct
JToggleButton()
JToggleButton(Icon i)
JToggleButton(Icon i, boolean selected)
JToggleButton(String text)
JToggleButton(String text, boolean selected)
JToggleButton(String text, Icon i)
JToggleButton(String text, Icon i, boolean selected)
Check Box
• The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of AbstractButton. Its immediate superclass is JToggleButton,
which provides support for two-state buttons.
Some of its constructors are shown here:
• 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)
Radio Buttons
• Radio buttons are supported by the JRadioButton class, which is a concrete
implementation of AbstractButton. Its immediate superclass is JToggleButton,
which provides support for two-state buttons.
• Some of its constructors are shown here:
• 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)
ButtonGroup
• Radio buttons must be configured into a group. Only one of the buttons in that group
can be selected at any time.
• For example, if a user presses a radio button that is in a group, any previously
selected button in that group is automatically deselected.
• The ButtonGroup class is instantiated to create a button group. Its default constructo
• is invoked for this purpose.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
/*<applet code="JRadioButtonDemo" width=300 height=50></applet>*/
public class JRadioButtonDemo extends JApplet implements ActionListener
{
JLabel jlab;
JRadioButton b1,b2,b3;
Panel p;
public void init()
{
Container c=getContentPane();
p=new Panel();
b1 = new JRadioButton("Information Technology");
b2 = new JRadioButton("Computer Engineering");
b3 = new JRadioButton("Electronics");
p.add(b1);
p.add(b2);
p.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
jlab = new JLabel("Select One");
p.add(jlab);
c.add(p);
}
public void actionPerformed(ActionEvent ae)
{
jlab.setText("You selected " + ae.getActionCommand());
}
}
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
/*<applet code="JRadioButtoncolor" width=300 height=50>
</applet>*/
public class JRadioButtoncolor extends JApplet implements ActionListener
{
JLabel jlab;
JRadioButton b1,b2,b3;
Panel p;
public void init()
{
Container c=getContentPane();
p=new Panel();
b1 = new JRadioButton("Red");
b2 = new JRadioButton("Green");
b3 = new JRadioButton("Blue");
p.add(b1);
p.add(b2);
p.add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
c.add(p);
}
public void actionPerformed(ActionEvent ae)
{
if(b1.isSelected())
p.setBackground(Color.RED);
else if(b2.isSelected())
p.setBackground(Color.GREEN);
else
p.setBackground(Color.BLUE);
}
}
Combo Boxes
• Swing provides a combo box (a combination of a text field and a drop-down list)
• through the JComboBox class, which extends JComponent.
• A combo box normallydisplays one entry. However, it can also display a drop-down
list that allows a user to select a different entry.
• JComboBox’s constructors are shown here:
JComboBox( )
JComboBox(Vector v)
JComboBox(Object[ ] items)

void addItem(Object obj)


Tabbed Panes
• JTabbedPane encapsulates a tabbed pane. It manages a set of components by
linking them with tabs.
• Selecting a tab causes the component associated with that tab to come to the
forefront.

• JTabbedPane uses the SingleSelectionModel model.


• Tabs are added by calling addTab( ).

void addTab(String name, Component comp)


Tabbed Panes
import javax.swing.*;
import java.awt.*;

/*<applet code="JTabbedPaneDemo" width=400 height=100></applet>*/

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());
add(jtp);
}
}
Tabbed Panes
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
setBackground(Color.GRAY);
JButton b1 = new JButton("Mumbai");
add(b1);
JButton b2 = new JButton("Pune");
add(b2);
JButton b3 = new JButton("Dehli");
add(b3);
JButton b4 = new JButton("Thane");
add(b4);
}
}
Tabbed Panes
class ColorsPanel extends JPanel
{

public ColorsPanel()
{
setBackground(Color.PINK);
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
Tabbed Panes
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
setBackground(Color.MAGENTA);
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
Tree
• Atree is a component that presents a hierarchical view of data.
• The user has the ability to expand or collapse individual subtrees in this display.
• Trees are implemented in Swing by the JTree class.
constructors are shown here:
JTree(Object obj[ ])
JTree(Vector<?> v)
JTree(TreeNode tn)

• Tree package is javax.swing.tree


• A JTree generates a variety of events, but three relate specifically to trees:
TreeExpansionEvent, TreeSelectionEvent, and TreeModelEvent.
• TreeExpansionEvent events occur when a node is expanded or collapsed.
• A TreeSelectionEvent is generated when the user selects or deselects a node
within the tree.
• A TreeModelEvent is fired when the data or structure of the tree changes.
• The listeners for these events are TreeExpansionListener, TreeSelectionListener,
and TreeModelListener, respectively.
• The tree event classes and listener interfaces are packaged in javax.swing.event.
• The DefaultMutableTreeNode class implements the MutableTreeNode interface.
• It represents a node in a tree.
• One of its constructors is shown here:
DefaultMutableTreeNode(Object obj)
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*
<applet code="JTreeDemo" width=400 height=200>
</applet>
*/
public class JTreeDemo extends JApplet implements TreeSelectionListener
{
JTree tree;
JLabel jlab;
public void init()
{
Container c=getContentPane();
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);
tree = new JTree(top);
c.add(tree);
jlab = new JLabel();
c.add(jlab, BorderLayout.SOUTH);
tree.addTreeSelectionListener(this);
}
public void valueChanged(TreeSelectionEvent tse)
{
jlab.setText("Selection is " + tse.getPath());
}
}
Scroll Pane
• JScrollPane is a lightweight container that automatically handles the scrolling of
another component.
• The viewable area of a scroll pane is called the viewport.
• It is a window in which the component being scrolled is displayed.
• Thus, the viewport displays the visible portion of the component being scrolled.
• JScrollPane will dynamically add or remove a scroll bar as needed.
• For example, if the component is taller than the viewport, a vertical scroll bar is
added. If the component will completely fit within the viewport, the scroll bars are
removed.
Construct
• JScrollPane(Component comp)
• HORIZONTAL_SCROLLBAR_ALWAYS Always provide horizontal scroll bar
• HORIZONTAL_SCROLLBAR_AS_NEEDED Provide horizontal scroll bar, if needed
• VERTICAL_SCROLLBAR_ALWAYS Always provide vertical scroll bar
• VERTICAL_SCROLLBAR_AS_NEEDED Provide vertical scroll bar, if needed
import java.awt.*;
import javax.swing.*;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JScrollPane;
/*
<applet code="JScrollpaneDemo" width=400 height=200>
</applet>
*/
public class JScrollpaneDemo extends JApplet
{
DefaultMutableTreeNode india,maharashtra,gujrat,mumbai,pune,nashik,nagpur;
public void init()
{
Container c=getContentPane();
india=new DefaultMutableTreeNode("India");
maharashtra=new DefaultMutableTreeNode("Maharashtra");
mumbai=new DefaultMutableTreeNode("Mumbai");
pune=new DefaultMutableTreeNode("Pune");
nashik=new DefaultMutableTreeNode("Nashik");
nagpur=new DefaultMutableTreeNode("Nagpur");
gujrat=new DefaultMutableTreeNode("Gujrat");
india.add(maharashtra);
maharashtra.add(mumbai);
maharashtra.add(pune);
maharashtra.add(nashik);
maharashtra.add(nagpur);
india.add(gujrat);

JTree jt=new JTree(india);


int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
JScrollPane js=new JScrollPane(jt,v,h);
c.add(js);
}
}
JTable
• JTable is a component that displays rows and columns of data.
• JTable has many classes and interfaces associated with it.
• These are packaged in javax.swing.table.
• It is a component that consists of one or more columns of information. At the top of each
column is a heading.
• JTable does not provide any scrolling capabilities of its own. Instead, we have to normally
wrap a JTable inside a JScrollPane.

Construct:
JTable(Object data[ ][ ], Object colHeads[ ])
JTable
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet {
public void init()
{
String[] colHeads = { "Name", "Extension", "ID#" };
Object[][] data = {
{ "Gail", "4567", "865" },
{ "Ken", "7566", "555" },
{ "Viviane", "5634", "587" },
{ "Melanie", "7345", "922" },
};
JTable
JTable table = new JTable(data, colHeads);
JScrollPane jsp = new JScrollPane(table);
add(jsp);
}
}
ToolTip
• We can add tooltip text to almost all the components of Java Swing by using
the setToolTipText(String s).
• This method sets the tooltip of the component to the specified string s .
• when the cursor enters the boundary of that component a popup appears
and text is displayed .

Methods used:
• getToolTipText() : returns the tooltip text for that component .
• setToolTipText(String s) : sets the tooltip text for the component .
Progress Bar
• JProgressBar visually displays the progress of some specified task.
• JProgressBar shows the percentage of completion of specified task.
• The progress bar fills up as the task reaches it completion. In addition to show the percentage
of completion of task.
• Constructors of JProgressBar :
• JProgressBar() : creates an progress bar with no text on it;
• JProgressBar(int orientation) : creates an progress bar with a specified orientation.
• if SwingConstants.VERTICAL is passed as argument a vertical progress bar is created, if
SwingConstants.HORIZONTAL is passed as argument a horizontal progress bar is created.
• JProgressBar(int min, int max) : creates an progress bar with specified minimum and
maximum value.
• JProgressBar(int orientation, int min, int max) : creates an progress bar with specified
minimum and maximum value and a specified orientation.
Commonly used methods of JProgressBar are :

int getMaximum() : returns the progress bar’s maximum value.


int getMinimum() : returns the progress bar’s minimum value.
String getString() : get the progress bar’s string representation of current value.
void setMaximum(int n) : sets the progress bar’s maximum value to the value n.
void setMinimum(int n) : sets the progress bar’s minimum value to the value n.
void setValue(int n) : set Progress bar’s current value to the value n.
void setString(String s) : set the value of the progress String to the String s.
MVC Architecture
• MVC (Model-View-Controller)
• In MVC terminology, the model corresponds to the state information associated with the
component. For example, in the case of a check box, the model contains a field that indicates
if the box is checked or unchecked.
• The view determines how the component is displayed on the screen, including any aspects of
the view that are affected by the current state of the model.
• The controller determines how the component reacts to the user. For example, when the user
clicks a check box, the controller reacts by changing the model to reflect the user’s choice
(checked or unchecked). This then results in the view being updated.
• By separating a component into a model, a view, and a controller, the specific implementation
of each can be changed without affecting the other two.
• For instance, different view implementations can render the same component in different ways
without affecting the model or the controller.

You might also like