You are on page 1of 24

Swing

Mr.P.M.Sawant.
Dept. Of Computer Science
Prof.Ramkirshna More ACS College,Akurdi
Email Id:sawanprasad@gmail.Com.

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

Swing is a widget toolkit for Java. It is part of Sun Microsystems' Java Foundation Classes (JFC) — an
API for providing a graphical user interface (GUI) for Java programs.Swing was developed to provide a
more sophisticated set of GUI components than the earlier Abstract Window Toolkit. Swing provides a
native look and feel that emulates the look and feel of several platforms, and also supports a pluggable
look and feel that allows applications to have a look and feel unrelated to the underlying platform.

Relationship to AWT
Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has provided platform-
independent APIs for user interface components. In AWT, each component is rendered and controlled by
a native peer component specific to the underlying windowing system.
By contrast, Swing components are often described as lightweight because they do not require allocation
of native resources in the operating system's windowing toolkit. The AWT components are referred to as
heavyweight components.
Much of the Swing API is generally a complementary extension of the AWT rather than a direct
replacement. In fact, every Swing lightweight interface ultimately exists within an AWT heavyweight
component because all of the top-level components in Swing (JApplet, JDialog, JFrame, and JWindow)
extend an AWT top-level container. However, the use of both lightweight and heavyweight components
within the same window is generally discouraged due to Z-order incompatibilities.
The core rendering functionality used by Swing to draw its lightweight components is provided by Java
2D, another part of JFC

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
JApplet

Constructor

JApplet()
Creates a swing applet instance.

Demo
import java.awt.*;
import javax.swing.*;
/*<applet code="JAppletDemo.class" width=300 height=200></applet>*/
public class JAppletDemo extends JApplet
{
public void init()
{
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
}
}

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

JFrame

Constructor Summary
JFrame()
Constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc)
reates 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.

Demo

import java.awt.*; Output


import javax.swing.*;
public class JFrameDemo
{
public static void main(String[] args)
{
JFrame f = new JFrame("JFrame Demo");
f.setSize(400, 150);
Container content = f.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
JLabel

Constructor Summary

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(Icon image, int horizontalAlignment)
Creates a JLabel instance with the specified image and horizontal alignment.
JLabel(String text)
Creates a JLabel instance with the specified text.
JLabel(String text, Icon icon, int horizontalAlignment)
Creates a JLabel instance with the specified text, image, and horizontal alignment.
JLabel(String text, int horizontalAlignment)
Creates a JLabel instance with the specified text and horizontal alignment.

Demo
import java.awt.*; Output
import javax.swing.*;
public class JLabelDemo extends JFrame
{
public static void main(String[] args)
{ new JLabelDemo(); }
public JLabelDemo()
{
JFrame f=new JFrame();
JLabel coloredLabel = new JLabel("Hello!",Label.CENTER);
Container c=getContentPane();
c.setLayout(new GridLayout(0,1));
c.add(coloredLabel);
pack();
f.add(c);
f.setVisible(true);
f.setSize(150,150);
}
}

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
JButton

Constructor Summary
JButton()
Creates a button with no set text or icon.
JButton(Action a)
Creates a button where properties are taken from the Action supplied.
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.

Demo
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonDemo extends JFrame implements ActionListener
{
private JButton btn_simple, btn_image;
public JButtonDemo()
{
setTitle("Testing Buttons");
Container container = getContentPane();
container.setLayout(new GridLayout(0,2));
btn_simple = new JButton("Simple Button");
btn_simple.setMnemonic(KeyEvent.VK_S);
container.add(btn_simple);
Icon bug1 = new ImageIcon("D:\\menu_1.gif");
btn_image = new JButton("Image",bug1);
btn_image.setMnemonic(KeyEvent.VK_I);
container.add(btn_image);
btn_image.addActionListener(this);
btn_simple.addActionListener(this);
setSize(300,100);
setVisible(true);
}
public static void main(String args[])
{ new JButtonDemo(); }
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(null,"You pressed: " +
ae.getActionCommand());
}
}

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

Output

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

JCheckBox

Constructor Summary
JCheckBox()
Creates an initially unselected check box button with no text, no icon.
JCheckBox(Action a)
Creates a check box where properties are taken from the Action supplied.
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.

Demo
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
class JCheckboxDemo
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frame.getContentPane();
Box box = new Box(BoxLayout.Y_AXIS);
cp.add(box);
box.add(new JLabel("Tick the sports you like..."));
String[] sports = {"Football", "Rugby", "Cricket","Badminton"};
JCheckBox[] cba = new JCheckBox[sports.length];
for (int i = 0; i < sports.length; i++)
{
cba[i] = new JCheckBox(sports[i]);
box.add(cba[i]);
}
frame.pack();
© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Output

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
JRadioButton

Constructor Summary
JRadioButton()
Creates an initially unselected radio button with no set text.
JRadioButton(Action a)
Creates a radiobutton where properties are taken from the Action supplied.
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.

Demo
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JRadioButtonDemo
{
public static void main(String[] args)
{
ActionListener listener = new ActionListener()
{
public void actionPerformed (ActionEvent e)
{ System.out.println(e.getActionCommand());}
};
Box p = new Box(BoxLayout.Y_AXIS);
ButtonGroup group = new ButtonGroup();
String[] sa = {"ugli","kiwi","passion","kumquat"};
for(int i=0;i<sa.length;++i) {
JRadioButton b = new JRadioButton(sa[i]);
group.add(b);
p.add(b);
b.addActionListener(listener);
}
JFrame frame = new JFrame("Fruits");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
frame.getContentPane().add(p);
frame.pack();
frame.setVisible(true);
}
}

Output

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

JTextField

Constructor Summary
JTextField()
Constructs a new TextField.
JTextField(Document doc, String text, int columns)
Constructs a new JTextField that uses the given text storage model and the given number of
columns.
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.

Demo

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

public class JLabelDemo extends JFrame


{
public JLabelDemo()
{
JTextField tf=new JTextField();
JFrame f = new JFrame("TextFieldDemo");
Container c= getContentPane();
c.setLayout(new GridLayout(0,2));
JLabel lbl1=new JLabel("TextField",SwingConstants.LEFT);
c.add(lbl1);
c.add(tf);
f.add(c);
f.setSize(300,100);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new JLabelDemo();
}
}

Output

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

JMenu

Constructor Summary
JMenu()
Constructs a new JMenu with no text.
JMenu(Action a)
Constructs a menu whose properties are taken from the Action supplied.
JMenu(String s)
Constructs a new JMenu with the supplied string as its text.
JMenu(String s, boolean b)
Constructs a new JMenu with the supplied string as its text and specified as a tear-off menu or
not.

Demo
import java.awt.*;
import javax.swing.*;
class JMenuDemo
{
public static void main(String[] args)
{
JMenu menu1 = new JMenu("File");
menu1.add(new JMenuItem("New"));
menu1.add(new JMenuItem("Open"));
menu1.add(new JSeparator());
menu1.add(new JMenuItem("Save"));
menu1.add(new JMenuItem("Save as..."));
menu1.add(new JSeparator());
menu1.add(new JMenuItem("Exit"));
JMenu menu2 = new JMenu("Edit");
menu2.add(new JMenuItem("Copy"));
menu2.add(new JSeparator());
menu2.add(new JMenuItem("Paste"));
menu2.add(new JSeparator());
menu2.add(new JMenuItem("Select ALL"));
JMenuBar bar = new JMenuBar();
bar.add(menu1);
bar.add(menu2);
JFrame frame = new JFrame();
frame.setJMenuBar(bar);
frame.setSize(350,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

Output

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

JColorChooser

Constructor Summary
JColorChooser()
Creates a color chooser pane with an initial color of white.
JColorChooser(Color initialColor)
Creates a color chooser pane with the specified initial color.
JColorChooser(ColorSelectionModel model)
Creates a color chooser pane with the specified ColorSelectionModel.

Demo
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorCh
{
static Container cp;
public static void main(String[] args)
{
final JFrame frame = new JFrame("Color Choice");
cp = frame.getContentPane( );
cp.setLayout(new GridBagLayout());
JButton button = new JButton("select color");
cp.add(button);
button.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(frame,"Choose a color", Color.red);
cp.setBackground(c);
}
});
frame.setSize(200, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

Select Any Color and Press OK

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

JOptionPane

Constructor Summary
JOptionPane()
Creates a JOptionPane with a test message.
JOptionPane(Object message)
Creates a instance of JOptionPane to display a message using the plain-message message type
and the default options delivered by the UI.
JOptionPane(Object message, int messageType)
Creates an instance of JOptionPane to display a message with the specified message type and
the default options,
JOptionPane(Object message, int messageType, int optionType)
Creates an instance of JOptionPane to display a message with the specified message type and
options.
JOptionPane(Object message, int messageType, int optionType, Icon icon)
Creates an instance of JOptionPane to display a message with the specified message type,
options, and icon.
JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options)
Creates an instance of JOptionPane to display a message with the specified message type, icon,
and options.
JOptionPane(Object message, int messageType, int optionType, Icon icon, Object[] options,
Object initialValue)
Creates an instance of JOptionPane to display a message with the specified message type, icon,
and options, with the initially-selected option specified.

Demo

import javax.swing.JOptionPane;
public class JOptionPaneDemo
{
public static void main(String[] args)
{
String[] choices = {"BJP", "NCP", "LEFT"};
int doAgain;
do
{
int response = JOptionPane.showOptionDialog
(
null, // center over parent
© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
"How did you vote?", // message
"Party Poll", // title in titlebar
JOptionPane.YES_NO_OPTION, // Option type
JOptionPane.PLAIN_MESSAGE, // messageType
null, // icon
choices, // Options
"None of your business" // initial value
);
JOptionPane.showMessageDialog(null, "Response = " + response);
doAgain = JOptionPane.showConfirmDialog(null, "Again?");
}
while(doAgain == JOptionPane.YES_OPTION);
System.exit(0); }

Output

Press Any One

After Pressing OK

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
JProgressBar

Constructor Summary

JProgressBar()
Creates a horizontal progress bar that displays a border but no progress string.

JProgressBar(BoundedRangeModel newModel)
Creates a horizontal progress bar that uses the specified model to hold the progress bar's data.

JProgressBar(int orient)
Creates a progress bar with the specified orientation, which can be either
SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.

JProgressBar(int min, int max)


Creates a horizontal progress bar with the specified minimum and maximum.

JProgressBar(int orient, int min, int max)


Creates a progress bar using the specified orientation, minimum, and maximum.

Demo

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.html.*;
public class SwingProgressBarExample
{
final static int interval = 1000;
int i;
JLabel label;
JProgressBar pb;
Timer timer;
JButton button;
public SwingProgressBarExample()
{
JFrame frame = new JFrame("Swing Progress Bar");
button = new JButton("Start");
button.addActionListener(new ButtonListener());
pb = new JProgressBar(0, 20);
pb.setValue(0);
pb.setStringPainted(true);
label = new JLabel("By Prasad Sawant");
JPanel panel = new JPanel();
panel.add(button);
panel.add(pb);
© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(panel, BorderLayout.NORTH);
panel1.add(label, BorderLayout.CENTER);
panel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
frame.setContentPane(panel1);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create a timer.
timer = new Timer(interval, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (i == 20)
{
Toolkit.getDefaultToolkit().beep();
timer.stop();
button.setEnabled(true);
pb.setValue(0);
String str = "<html>" + "<font color=\"#FF0000\">" + "<b>" +
"Downloading completed." + "</b>" + "</font>" + "</html>";
label.setText(str);
}
i = i + 1;
pb.setValue(i);
}});
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
button.setEnabled(false);
i = 0;
String str = "<html>" + "<font color=\"#008000\">" + "<b>" +
"Downloading is in process......." + "</b>" + "</font>" + "</html>";
label.setText(str);
timer.start();
}
}
public static void main(String[] args)
{
SwingProgressBarExample spb = new SwingProgressBarExample();
}
}

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

After Pressing Start Button

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing
JSpinner

A single line input field that lets the user select a number or an object value from an ordered sequence.
Spinners typically provide a pair of tiny arrow buttons for stepping through the elements of the sequence.
The keyboard up/down arrow keys also cycle through the elements. The user may also be allowed to type
a (legal) value directly into the spinner. Although combo boxes provide similar functionality, spinners are
sometimes preferred because they don't require a drop down list that can obscure important data.

A JSpinner's sequence value is defined by its SpinnerModel. The model can be specified as a constructor
argument and changed with the model property. SpinnerModel classes for some common types are
provided: SpinnerListModel, SpinnerNumberModel, and SpinnerDateModel.

A JSpinner has a single child component that's responsible for displaying and potentially changing the
current element or value of the model, which is called the editor. The editor is created by the JSpinner's
constructor and can be changed with the editor property. The JSpinner's editor stays in sync with the
model by listening for ChangeEvents. If the user has changed the value displayed by the editor it is
possible for the model's value to differ from that of the editor. To make sure the model has the same
value as the editor use the commitEdit method

Demo

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
class JSpinnerExample
{
public static void main(String[] args)
{
String[] sizes = {"small","medium","large","XL","XXL"};
final SpinnerListModel model = new SpinnerListModel(sizes);
JSpinner jSpinner = new JSpinner(model);
model.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println(model.getValue());
}
});
JFrame frame = new JFrame();
frame.setSize(100,100);

frame.getContentPane().add(jSpinner);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi


Swing

Press UP KEY

Press UP KEY

© Dept. Of Computer Science

Prof.Ramkirshna More ACS College,Akurdi