You are on page 1of 39

Unit –II Swing

Mundhe Shankar G
Lecturer In IT
Government Polytechnic Nanded
Introduction to Swing
• Swing API is a set of extensible GUI Components .
• It is build on top of AWT API and acts as a replacement of AWT API, since it
has almost every control corresponding to AWT controls.
• Swing component follows a Model-View-Controller.
– Model represents component's data.
– View represents visual representation of the component's data.
– Controller takes the input from the user on the view and reflects the
changes in Component's data.
• Swing Features
• Light Weight − Swing components are independent of native Operating
System's API. (Swing is Entirely written in Java)
• Rich Controls − Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, colorpicker, and table controls.
• Highly Customizable − Swing controls can be customized in a very easy way
as visual appearance is independent of internal representation.
• Pluggable look-and-feel − SWING based GUI Application look and feel can be
changed at run-time, based on available values.
Swing Components
• JButton
• Constructors
• JButton() It creates a button with no text and icon.
• JButton(String s) It creates a button with the specified text.
• JButton(Icon i) It creates a button with the specified icon object.
Mnemonic ---- one letter with underline
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
• JCheckBox
• public class JCheckBox extends JToggleButton implements Accessible

• Commonly used Constructors:


• JCheckBox()-Creates an initially unselected check box button with no text, no icon.

• JChechBox(String s)-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(Action a)-Creates a check box where properties are taken from the Action
supplied.

• Commonly used Methods


• AccessibleContext getAccessibleContext()- It is used to get the AccessibleContext
associated with this JCheckBox.
• protected String paramString()- It returns a string representation of this JCheckBox.
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++“,true);
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String args[]) { new CheckBoxExample(); }


}
JRadioButton
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2; JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300); setLayout(null); setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male."); }
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female."); }
}
public static void main(String args[]){ new RadioButtonExample(); }
}
class ImageIconExample1 extends JFrame{
ImageIconExample1() {
setTitle("ImageIcon");
ImageIcon icon = new ImageIcon("india.png");
JLabel jl = new JLabel("Indian Flag",icon,JLabel.CENTER);
add(jl);

setSize(700, 200);
setLayout(new FlowLayout());
//setLabel();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

public class ImageIconExample{


public static void main(String[] args){
//ImageIconExample1 f5 =
new ImageIconExample1();
}
}
JApplet
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;

public class EventJApplet extends JApplet implements ActionListener{


JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);

b=new JButton("Click");
b.setBounds(80,150,70,40);

add(b);add(tf);
b.addActionListener(this);

setLayout(null);
}

public void actionPerformed(ActionEvent e){


tf.setText("Welcome");
}
}
• ( USE html File for applet Tag)
JLabel
• Commonly used Constructors

• JLabel() -Creates a JLabel instance with no image and with an empty


string for the title.

• JLabel(String s)- Creates a JLabel instance with the specified text.

• JLabel(Icon i)- Creates a JLabel instance with the specified image.

• JLabel(String s, Icon i, int horizontalAlignment) - Creates a JLabel instance


with the specified text, image, and horizontal alignment.
• Commonly Used Methods of JLabel
• String getText()-
– returns the text string that a label displays.

• void setText(String text)


– -It defines the single line of text this component will display.

• void setHorizontalAlignment(int alignment)


– It sets the alignment of the label's contents along the X axis.

• Icon getIcon()-
– It returns the graphic image that the label displays.

• int getHorizontalAlignment()
– It returns the alignment of the label's contents along the X axis.
import javax.swing.*;

class LabelExample {
public static void main(String args[]) {
JFrame f = new JFrame("Label Example");
JLabel l1, l2;
l1 = new JLabel("Govt Poly Nanded");
l1.setBounds(50, 50, 100, 30);
l2 = new JLabel("IT Dept");
l2.setBounds(50, 100, 100, 30);
f.add(l1);
f.add(l2);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField
• The object of a JTextField class is a text component that allows the editing of a
single line text

• Commonly Used Constructors.


• JTextField()
– Creates a new TextField
• JTextField(String text)
– Creates a new TextField initialized with the specified text.
• JTextField(String text, int columns)
– Creates a new TextField initialized with the specified text and columns.
• JTextField(int columns)
– Creates a new empty TextField with the specified number of columns.
• Commonly Used Methods

• void addActionListener(ActionListener l)
– It is used to add the specified action listener to receive action events from this textfield.
• Action getAction()
– It returns the currently set Action for this ActionEvent source, or null if no Action is set.
• void setFont(Font f)
– It is used to set the current font.
• void removeActionListener(ActionListener l)
– It is used to remove the specified action listener so that it no longer receives action events
from this textfield.
import javax.swing.*;
class TextFieldExample {
public static void main(String args[]) {
JFrame f = new JFrame("Government Polytechnic Nanded");
JTextField t1, t2;
t1 = new JTextField("Information Technology ");
t1.setBounds(50, 100, 200, 30);
t2 = new JTextField("Advance Java ");
t2.setBounds(50, 150, 200, 30);

f.add(t1);
f.add(t2);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}
JComboBox
• public class JComboBox extends JComponent implements ItemSelectable, List
DataListener, ActionListener, Accessible

• Commonly used Constructors:


• 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
• Commonly used Methods:
• void addItem(Object anObject)
– It is used to add an item to the item list.
• void removeItem(Object anObject)
– It is used to delete an item to the item list.
• void removeAllItems()
– It is used to remove all the items from the list.
• void setEditable(boolean b)
– It is used to determine whether the JComboBox is editable.
• void addActionListener(ActionListener a)
– It is used to add the ActionListener
• .void addItemListener(ItemListener i)
– It is used to add the ItemListener
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);

f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
JTabbedPane
• The JTabbedPane class is used to switch between a group of components by
clicking on a tab with a given title or icon.

• public class JTabbedPane extends JComponent implements Serializable, Accessi


ble, SwingConstants

• Commonly Used Constructors


• JTabbedPane()
– Creates an empty TabbedPane with a default tab placement of JTabbedPane.Top.
• JTabbedPane(int tabPlacement)
– Creates an empty TabbedPane with a specified tab placement.
• JTabbedPane(int tabPlacement, int tabLayoutPolicy)
– Creates an empty TabbedPane with a specified tab placement and tab layout policy.
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JButton b1=new JButton("submit");
p2.add(b1);
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);

f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) { new TabbedPaneExample(); }
}
JScrollPane
• A JscrollPane is used to make scrollable view of a component. When screen
size is limited, we use a scroll pane to display a large component or a
component whose size can change dynamically.
• Constructors
• JScrollPane()- It creates a scroll pane.

• JScrollPane(Component)- The Component parameter, when present, sets


the scroll pane's client.

• JScrollPane(int, int)-The two int parameters, when present, set the vertical
and horizontal scroll bar policies (respectively).

• JScrollPane(Component, int, int)


import javax.swing.*;
import java.awt.*;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;

private static void createAndShowGUI() {


final JFrame frame = new JFrame("Scroll Pane Example");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());

JTextArea textArea = new JTextArea(20, 20);


JScrollPane scrollableTextArea = new JScrollPane(textArea);

scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {


createAndShowGUI();
}
});
}
}
JTree
• public class JTree extends JComponent implements Scrollable, Accessible

• Commonly used Constructors:


• JTree()
– Creates a JTree with a sample model.
• JTree(Object[] value)
– Creates a JTree with every element of the specified
array as the child of a new root node.
• JTree(TreeNode root)
– Creates a JTree with the specified TreeNode as its
root, which displays the root node.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);

DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");


DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");

color.add(red); color.add(blue); color.add(black); color.add(green);


JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) { new TreeExample(); }
}
JTable
• Commonly used Constructors:
• JTable()
– Creates a table with empty cells.
• JTable(Object[][] rows, Object[] columns)
– Creates a table with the specified data.
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};

JTable jt=new JTable(data,column);


jt.setBounds(30,40,200,300);

JScrollPane sp=new JScrollPane(jt);


f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
JProgressBar
• public class JProgressBar extends JComponent implements SwingConstants, Ac
cessible
• Commonly used Constructors:
• JProgressBar()
– It is used to create a horizontal progress bar but no string text.
• JProgressBar(int min, int max)
– It is used to create a horizontal progress bar with the specified minimum and maximum value.
• JProgressBar(int orient)
– It is used to create a progress bar with the specified orientation, it can be either Vertical or
Horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants.
• JProgressBar(int orient, int min, int max)
– It is used to create a progress bar with the specified orientation, minimum and maximum
value.
• Commonly used Methods:

• void setStringPainted(boolean b)
– It is used to determine whether string should be displayed.
• void setString(String s)
– It is used to set value to the progress string.
• void setOrientation(int orientation)
– It is used to set the orientation, it may be either vertical or horizontal by using
SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants.
• void setValue(int value)
– It is used to set the current value on the progress bar.
import javax.swing.*;

public class ProgressBarExample extends JFrame {


JProgressBar jb; int i = 0;

ProgressBarExample() {
jb = new JProgressBar(0, 100);
jb.setBounds(40, 40, 160, 30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250, 150);
setLayout(null);
}

public void iterate() {


while (i <= 100) {
jb.setValue(i);
i = i + 5;
try {
Thread.sleep(150);
} catch (Exception e) { }
}
}

public static void main(String[] args) {


ProgressBarExample m = new ProgressBarExample();
m.setVisible(true);
m.iterate();
}
}
ToolTip
• ou can create a tool tip for any Jcomponent with setToolTipText() method. This
method is used to set up a tool tip for the component.

import javax.swing.*;
public class ToolTipExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");

JPasswordField value = new JPasswordField();


value.setBounds(100,100,100,30);
value.setToolTipText("Enter your Password");
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
MVC Architecture
• Model
• The Model component corresponds to all the data-related logic that the
user works with. This can represent either the data that is being
transferred between the View and Controller components or any other
business logic-related data. For example, a Customer object will retrieve
the customer information from the database, manipulate it and update it
data back to the database or use it to render data.
• View
• The View component is used for all the UI logic of the application. For
example, the Customer view will include all the UI components such as
text boxes, dropdowns, etc. that the final user interacts with.
• Controller
• Controllers act as an interface between Model and View components to
process all the business logic and incoming requests, manipulate data
using the Model component and interact with the Views to render the
final output. For example, the Customer controller will handle all the
interactions and inputs from the Customer View and update the database
using the Customer Model. The same controller will be used to view the
Customer data.
• The End

You might also like