0% found this document useful (0 votes)
21 views34 pages

M5 - 3 - Swing Packages, Event Handling in Swings.

its a java material

Uploaded by

radhika.km
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views34 pages

M5 - 3 - Swing Packages, Event Handling in Swings.

its a java material

Uploaded by

radhika.km
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

CS205 Object Oriented Programming in

Java
Module 5 - Graphical User Interface and
Database support of Java
(Part 3)
Prepared by
Renetha J.B.
AP
Dept.of CSE,
Lourdes Matha College of Science and Technology

Prepared by Renetha J.B. 1


Topics

Swings
Swing Packages

Event Handling in Swings.

Prepared by Renetha J.B. 2


Swing Packages
• Swing is a very large subsystem and makes use of many
packages.

– These are the packages used by Swing that are defined by


Java SE 6.

• The main package is javax.swing.

– This package must be imported into any program that


uses Swing.

– It contains the classes that implement the basic Swing


components, such as push buttons, labels, and check
boxes. Prepared by Renetha J.B. 3
Swing packages(contd.)
javax.swing javax.swing.border javax.swing.colorchooser

javax.swing.event javax.swing.filechooser javax.swing.plaf

javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi

javax.swing.plaf.synth javax.swing.table javax.swing.text

javax.swing.text.html javax.swing.text.html.par javax.swing.text.rtf


ser

javax.swing.tree javax.swing.undo

Prepared by Renetha J.B. 4


A Simple Swing Application
• There are two types of Java programs in which Swing is
typically used.

1. desktop application.

2. applet

Prepared by Renetha J.B. 5


A Simple Swing Application
• Q. Write a swing program that uses two Swing components:
Jframe and JLabel. The program uses a JFrame container
to hold an instance of a JLabel. The label displays a short text
message

• JFrame is the top-level container that is commonly used for


Swing applications. JLabel is the Swing component that
creates a label, which is a component that displays
information. The label is Swing’s simplest component
because it is passive.

– That is, a label does not respond to user input. It just


displays output.

Prepared by Renetha J.B. 6


import javax.swing.*;
class SwingDemo
{
SwingDemo()
{
// Create a new JFrame container. With title- A Simple Swing
JFrame jfrm = new JFrame("A Simple Swing ");

// Give the frame an initial size. Width=275 height =100


jfrm.setSize(275, 100);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Prepared by Renetha J.B. 7


// Create a text-based label
JLabel jlab = new JLabel(" Swing is powerful GUI");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame. Too compile this program,
jfrm.setVisible(true); javac SwingDemo.java
} To run the program,
java SwingDemo
public static void main(String args[])
{
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
new SwingDemo();
}
}
);
} }
Prepared by Renetha J.B. 8
// A simple Swing application. JLabel jlab = new JLabel(" Swing is
import javax.swing.*; powerful GUI");
// Add the label to the content pane.
class SwingDemo {
jfrm.add(jlab);
SwingDemo() { // Display the frame.
// Create a new JFrame container. jfrm.setVisible(true);
JFrame jfrm = new JFrame("A Simple Swing "); }
// Give the frame an initial size. public static void main(String args[])
{
jfrm.setSize(275, 100); // Create the frame on the event
// Terminate the program when the user closes dispatching thread.
the application. SwingUtilities.invokeLater(new
Runnable() {
jfrm.setDefaultCloseOperation(JFrame.EXI
public void run() {
T_ON_CLOSE);
new SwingDemo();
// Create a text-based label }
});
}
}
Prepared by Renetha J.B. 9
• javax.swing defines classes that implement labels, buttons,
text controls, and menus.
• The constructor is where most of the action of the program
occurs. It begins by creating a JFrame, using this line of code:
JFrame jfrm = new JFrame("A Simple Swing ");
• This creates a container called jfrm that defines a rectangular
window complete with a title bar; close, minimize,
maximize, and restore buttons; and a system menu.
• Thus, it creates a standard, top-level window.
• The title of the window is passed to the constructor
– Here title is A Simple Swing
Prepared by Renetha J.B. 10
• The window is sized using this statement:
jfrm.setSize(275, 100);
• The setSize( ) method (which is inherited by JFrame from the
AWT class Component) sets the dimensions of the window,
which are specified in pixels. Its general form :
void setSize(in t width, int height)

• We want the entire application to terminate when its top-


level window is closed. There are a couple of ways to achieve
this. The easiest way is to call setDefaultCloseOperation( ),
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
• After this call executes, closing the window causes the entire
application to terminate.
Prepared by Renetha J.B. 11
• The general form of setDefaultCloseOperation( ) is :
void setDefaultCloseOperation(int what)

– The value passed in what determines what happens when the


window is closed.
• There are several options :
JFrame.EXIT_ON_CLOSE
JFrame.DISPOSE_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE

Prepared by Renetha J.B. 12


• The next line of code creates a Swing JLabel component:

JLabel jlab = new JLabel(" Swing is powerful GUI");

• The next line of code adds the label to the content pane of the
frame:

jfrm.add(jlab);

• Thus, to add a component to a frame, we must add it to the


frame’s content pane. This is accomplished by calling add( )
on the JFrame reference (jfrm in this case). The general
form of add( ) is:

Component add(Component comp)


Prepared by Renetha J.B. 13
• The content pane can be obtained by calling getContentPane( )
on a JFrame instance

Container getContentPane( )

• The last statement in the SwingDemo constructor causes the


window to become visible:

jfrm.setVisible(true);

Prepared by Renetha J.B. 14


• SwingDemo constructor is invoked using the following lines of
code:
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
new SwingDemo();
}
}
);
• This sequence causes a SwingDemo object to be created on the
event dispatching thread rather than on the main thread of the
application.
• Swing programs are event-driven.
Prepared by Renetha J.B. 15
• To enable the GUI code to be created on the event
dispatching thread, we must use one of two methods that are
defined by the SwingUtilities class.
• These methods are
– invokeLater( )
– invokeAndWait( ).
static void invokeLater(Runnable obj)
static void invokeAndWait(Runnable obj)
throws InterruptedException, InvocationTargetException

• The difference between the two methods is that


– invokeLater() returns immediately,
– but invokeAndWait( ) waits until obj.run( ) returns
Prepared by Renetha J.B. 16
Event Handling in Swings
• Delegation event model is the event handling mechanism
used by Swing.

• Swing uses the same events as does the AWT, and these events
are packaged in java.awt.event.

• Events specific to Swing are stored in javax.swing.event

Prepared by Renetha J.B. 17


Swing-Event handling E.g.
• Q. Write a program in swing to create a frame with title “An
Event Example ”.
– Give FlowLayout to frame and set a width =220 and height=90
– Frame has two buttons Ok and Cancel.
– Frame has a label that display the message “Push a button”.
– When we click the OK button it prints the message “OK
pressed” in the label.
– When we click the Cancel button it prints the message “Cancel
pressed” in the label

Prepared by Renetha J.B. 18


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo extends JFrame implements ActionListener
{ JLabel jlab;
EventDemo()
{ // Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
jfrm.setSize(220, 90);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.
JButton jbtnOk = new JButton("OK");
JButton jbtnCancel = new JButton("Cancel");
Prepared by Renetha J.B. 19
// Add action listener for Ok button.
jbtnOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jlab.setText("OK pressed.");
}
}
);
// Add action listener for Cancel button.
jbtnCancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jlab.setText("Cancel pressed.");
}
}
);

Prepared by Renetha J.B. 20


// Add the buttons to the content pane.
jfrm.add(jbtnOk);
jfrm.add(jbtnCancel);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}

Prepared by Renetha J.B. 21


public static void main(String args[])
{
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new EventDemo();
}
}
);
}
}

Prepared by Renetha J.B. 22


• The java.awt package is needed because
– it contains the FlowLayout class, which supports the
standard flow layout manager used to lay out components
in a frame
– It defines the ActionListener interface and the ActionEvent
class.
• The EventDemo constructor begins by creating a JFrame
called jfrm with title -An Event Example
JFrame jfrm = new JFrame("An Event Example");
• It then sets thelayout manager for the content pane of jfrm to
FlowLayout.
jfrm.setLayout(new FlowLayout());
• By default, the content pane uses BorderLayout as its layout
manager.
Prepared by Renetha J.B. 23
• After setting the size and default close operation,
EventDemo() creates two push buttons, as shown here:
JButton jbtnOk = new JButton(“Ok");
JButton jbtnCancel = new JButton(”Cancel");
– The first button will contain the text “Ok” and the second will
contain the text “Cancel”.

• When a push button is pressed, it generates an ActionEvent.


• Thus, JButton provides the addActionListener( ) method,
which is used to add an action listener so that button will
respond to events. (JButton also provides
removeActionListener( ) to remove a listener)

Prepared by Renetha J.B. 24


• event listeners for the button’s action events are added by the code shown belo:
• // Add action listener for Ok button.
jbtnOK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{ jlab.setText(“OKwas pressed.");
}
});
This can also be written as:
jbtnOK.addActionListener(this);
…………………………………
}
public void actionPerformed(ActionEvent ae)
{ String s = ae.getActionCommand(); //to get the name written in button
if(s.equalsIgnoreCase("ok")) //to have case insensitive comparison
jlab.setText("OK pressed.");
} Prepared by Renetha J.B. 25
Simple Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemoSwing extends JFrame implements ActionListener
{ JLabel jlab;
EventDemoSwing()
{ JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtnOk = new JButton("OK");
JButton jbtnCancel = new JButton("Cancel");
jbtnOk.setToolTipText("click");
jbtnOk.addActionListener(this);
jbtnCancel.addActionListener(this);
jfrm.add(jbtnOk);
jfrm.add(jbtnCancel);
jlab = new JLabel("Press a button.");
jfrm.add(jlab);
jfrm.setVisible(true);
} Prepared by Renetha J.B. 26
public void actionPerformed(ActionEvent ae)
{ //store the name written in button that is clicked ,in variable s
String s = ae.getActionCommand();
if(s.equalsIgnoreCase("ok"))
jlab.setText("OK pressed.");
else if(s.equalsIgnoreCase("cancel"))
jlab.setText("Cancel pressed.");
}
public static void main(String args[])
{ SwingUtilities.invokeLater(new Runnable()
{ public void run()
{
new EventDemoSwing();
}
}
);
}
Prepared by Renetha J.B. 27
}
Create a Swing Applet
• A Swing applet extends Japplet.
– JApplet is derived from Applet.
• Swing applets use the same four lifecycle methods as
Applet
• init( ),
• start( ), stop( ), and destroy( ).
• Swing applet will not normally override the paint( )
method

Prepared by Renetha J.B. 28


• Write a program using SWING APPLET
– It should have two buttons Ok and Cancel.
– Label to display message “Push a button”.
– When we click the OK button it prints the message “OK
pressed” in the label.
– When we click the Cancel button it prints the message “Cancel
pressed” in the label

Prepared by Renetha J.B. 29


// A simple Swing-based applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
This HTML can be used to launch the applet:
<object code="MySwingApplet" width=220 height=90>
</object>
*/
public class MySwingApplet extends JApplet implements ActionListener
{
JButton jbtnOk;
JButton jbtnCancel;
JLabel jlab;

Prepared by Renetha J.B. 30


// Initialize the applet.
public void init() {
try { SwingUtilities.invokeAndWait(new Runnable ()
{
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc)
{
System.out.println("Can't create because of "+ exc); }
}

Prepared by Renetha J.B. 31


private void makeGUI()
{ // Set the applet to use flow layout.
setLayout(new FlowLayout());
// Make two buttons.
jbtnOk = new JButton("Ok");
jbtnCancel = new JButton("Cancel");
// Add action listener for ok.
jbtnOk.addActionListener(this);
// Add action listener for Cancel.
jbtnCancel.addActionListener(this);
// Add the buttons to the content pane.
add(jbtnOk);
add(jbtnCancel);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
add(jlab);
} Prepared by Renetha J.B. 32
public void actionPerformed(ActionEvent ae)
{
String s = ae.getActionCommand();
if(s.equalsIgnoreCase("Ok"))
jlab.setText("Ok was pressed.");
else if(s.equalsIgnoreCase("Cancel"))
jlab.setText("Cancel was pressed.");
}
} COMPILE
javac MySwingApplet.java

RUN
appletviewer MySwingApplet.java

Prepared by Renetha J.B. 33


Reference
• Herbert Schildt, Java: The Complete Reference, 8/e,
Tata McGraw Hill, 2011.

Prepared by Renetha J.B. 34

You might also like