Java Swing
Java Swing
Swing
Java Swing is a part of Java Foundation Classes (JFC)that is used to
create window-based applications.
Swing Is Built on the AWT(Abstract Windowing Toolkit) API and entirely
written in java.
The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
Swing Features
The AWT defines a basic set of controls, windows, and dialog boxes that support
a usable, but limited graphical interface.
One reason for the limited nature of the AWT is that it translates its various
visual components into their corresponding, platform-specific equivalents.
Java AWT components are platform-dependent i.e. components
are displayed according to the view of operating system.
AWT is heavyweight i.e. its components are using the resources of
OS.
Why Swing ?
The look and feel of a component is defined by the platform,
not by Java.
The way that the component looks when rendered on the screen.
BROWSER CONTROLLER
Handles
Decision
Handles Presentation Handles Data
The main package must be imported into any program that uses
Swing.
Types of Swing Program
There are two types of Java programs in which Swing is typically used.
Desktop application.
Applet.
The desktop application uses two Swing components: JFrame and JLabel.
The program uses a Jframe container to hold an instance of a JLabel.
JLabel
Swing component.
The label is Swings simplest component because it is passive.
Does not respond to user input. It just displays output.
Frame in swing
Creating a frame
Frame represent a window with a title bar and borders.
The basis for creating a screens for an application because all the
components go into the frame.
SYNTAX:
JFrame object = new Jframe();//create a frame without a title.
JFrame object= new JFrame(TITLE);//create a frame with a title.
Creating a frame in swing
Import javax.swing.*;
Class DemoSwing
{
public static void main(String args[])
{
//create a frame with a title;
JFame jf= new JFrame (JFRAME DEMO);
jf.setSize(200,200);//initial size of frame is 0px width & 0px height which is no
visible
jf.setVisible(true);
}
}
Frame in swing
Closing an application:
SYNTAX:
getDefaultCloseOperation(constant);
Where constant can be:
JFrame.EXIT_ON_CLOSE(close on clicking close button)
JFrame.DISPOSE_ON_CLOSE(disposes the current frame which is visible on screen)
JFrame.HIDE_ON_CLOSE(hides the frame)
JFrame.DO_NOTHING_ON_CLOSE(performs no operation)
Creating a frame in swing
Import javax.swing.*;
Class DemoSwing
{ public static void main(String args[])
{ JFame jf= new JFrame (JFRAME DEMO); //create a frame with a title;
jf.setSize(200,200);//initial size of frame is 0px width & 0px height which is no visible
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//close the application upon
clicking on close button of frame
JLabel jlab = new JLabel(" Swing means powerful GUIs.");// Create a text-based label
jf.add(jlab); // Add the label to the content pane.
}
}
Example of Swing by Association inside
constructor
import javax.swing.*;
public class Simple {
Simple(){
JFrame f =new JFrame();//creating instance of JFrame
f.setSize(400,500);//400 width and 500 height
f.setVisible(true);//making the frame visible
f.setDefaultOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{ new Simple();
}
}
Event Handling
What is an Event?
Change in the state of an object is known as Event, i.e., event describes the
change in the state of the source.
Events are generated as a result of user interaction with the graphical user
interface components.
Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs. This mechanism has a code
which is known as an event handler, that is executed when an event
occurs.
Java uses the Delegation Event Model to handle the events. This
model defines the standard mechanism to generate and handle the
events.
Event Handling - Delegation Event Model
The Delegation Event Model has the following key participants.
Source
The source is an object on which the event occurs.
Source is responsible for providing information of the occurred event to it's
handler. Java provide us with classes for the source object.
Listener
It is also known as event handler.
The listener is responsible for generating a response to an event.
From the point of view of Java implementation, the listener is also an object.
The listener waits till it receives an event.
Once the event is received, the listener processes the event and then returns.
Event Handling - Delegation Event Model
In this model, the listener needs to be registered with the source object
so that the listener can receive the event notification.
This is an efficient way of handling the event because the event
notifications are sent only to those listeners who want to receive them.
Event Handling
The event handling mechanism used by Swing is the same as that
used by the AWT.
In many cases, 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.
The package java.awt.event defines many types of events that are
generated by various user interface elements.
Event Class Description
import java.io.PrintStream;
static class TestAnonymousInner$1 extends Person
{
TestAnonymousInner$1(){}
void eat()
{
System.out.println("nice fruits");
}
}
Explanation anonymous class
Event dispatching thread
object
JApplet is derived from Applet. Thus, JApplet includes all of the functionality
found in Applet and adds support for Swing.
JApplet is a top-level Swing container, which means that it is not derived from
JComponent.
All components are added to JApplets content pane in the same way that
components are added to JFrames content pane.
SwingUtilities Class
To avoid problems (including the potential for deadlock), all Swing GUI components
must be created and updated from the event dispatching thread, not the main
thread of the application.
invokeLater() invokeAndWait()
static void invokeLater(Runnable obj) static void invokeAndWait(Runnable obj)
Where obj is a Runnable object that will
have its run() method called by the event
dispatching thread.
returns immediately waits until obj.run( ) returns
Swing Applet EXAMPLE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MySwingApplet extends JApplet {
JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable () {
public void run() { makeGUI(); }
});
}
catch(Exception exc) {
System.out.println("Can't create because of "+ exc); }
}
Swing Applet EXAMPLE
private void makeGUI() { // Add action listener for Beta.
SYNTAX:
public class JPanel extends JComponent implements Accessible
Commonly used Constructors
Constructor Description
JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout
manager.
Java JPanel Example
import java.awt.*; b2.setBounds(100,100,80,30);
import javax.swing.*; b2.setBackground(Color.green);
public class PanelExample {
panel.add(b1); panel.add(b2);
PanelExample()
f.add(panel);
{
JFrame f= new JFrame("Panel Example");
f.setSize(400,400);
JPanel panel=new JPanel(); f.setLayout(null);
panel.setBounds(40,80,200,200); f.setVisible(true);
panel.setBackground(Color.gray); }
JButton b1=new JButton("Button 1"); public static void main(String args[])
b1.setBounds(50,100,80,30); {
b1.setBackground(Color.yellow);
new PanelExample();
JButton b2=new JButton("Button 2");
}
}
Java JTextField
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
Text Field1 Example
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
Text Field2 Example
t1=new JTextField(Text Field1 Example");
t1.setBounds(50,100, 200,30);
t2=new JTextField(" Text Field2 Example ");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); } }
Java JTextField Example with ActionListener
import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20); // setBounds(int x, int y, int width, int height)
x the the number of pixels from the left of the screen and y is is the number from the top of the screen
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false); // prevent the user from entering text into the wrong text field
b1=new JButton("+"); int a=Integer.parseInt(s1);
b1.setBounds(50,200,50,50); int b=Integer.parseInt(s2);
b2=new JButton("-"); int c=0;
b2.setBounds(120,200,50,50); if(e.getSource()==b1)
b1.addActionListener(this); //The getSource( ) method returns the source of the event.
b2.addActionListener(this); {
f.add(tf1);f.add(tf2);f.add(tf3); c=a+b;
f.add(b1);f.add(b2); }else if(e.getSource()==b2){
f.setSize(300,300); c=a-b;
f.setLayout(null); }
f.setVisible(true); String result=String.valueOf(c);
} tf3.setText(result);
public void actionPerformed(ActionEvent e) { }
public static void main(String[] args) {
new TextFieldExample();
String s1=tf1.getText(); }}
String s2=tf2.getText();
Output
Creating A Form
Click here
Next page Example
and LoginPage