Sie sind auf Seite 1von 53

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

Swing Components Are Lightweight.

They are written entirely in Java and do not map directly to


platform-specific peers.

Which enables nonrectangular shapes.

Lightweight components are more efficient and more


flexible.

Swing Supports a Pluggable Look and Feel.


Why Swing ?
Deficiencies present in Javas original GUI subsystem: the Abstract Window
Toolkit(AWT).

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.

Because of variations between operating systems, a component


might look, or even act, differently on different platforms. Which
leads to the problem : write once, run anywhere.

The look and feel of each component was fixed (because it is


defined by the platform) and could not be (easily) changed.

The use of heavyweight components caused some frustrating


restrictions.
For example, a heavyweight component is always rectangular
and opaque.
Difference between AWT and Swing
JAVA AWT JAVA SWING
AWT components are platform-dependent. Java swing components are platform-
independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and Swing supports pluggable look and feel.
feel.
AWT provides less components than Swing. Swing provides more powerful components
such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.

AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as
an interface between model and view.
Fig: Hierarchy of Java AWT
classes
Fig: Hierarchy of Java Swing
classes
The MVC(Model View-controller)
In general, a visual component is a composite of three distinct aspects:

The way that the component looks when rendered on the screen.

The way that the component reacts to the user.

The state information associated with the component.


The MVC(Model View-controller)
represents an object
MODEL

View represents the visualization of the data


that model contains.
VIEW

Controller acts on both model and view. It


controls the data flow into model object and
updates the view whenever data changes. It CONTROLLER
keeps view and model separate
BASIC web architecture

BROWSER PAGE Database


BASIC web architecture

BROWSER CONTROLLER

Handles
Decision
Handles Presentation Handles Data

VIEW MODEL Database


COMPONENTS AND CONTAINER
A Swing GUI consists of two key items: components and containers.
The difference between the two is found in their intended purpose:
a component is an independent visual control, such as a push button or slider
A container holds a group of components thus a container is a special type
of component that is designed to hold other components.
All Swing GUIs will have at least one container.
A container can also hold other containers
This enables Swing to define what is called a containment hierarchy, at the
top of which must be a top-level container.
Components
Swing components are derived from the JComponent class.
JComponent provides the functionality that is common to all
components.[JComponent supports the pluggable look and feel]
JComponent inherits the AWT classes Container and Component.
A Swing component is built on and compatible with an AWT component.
All Swings components are represented by classes defined within the package
javax.swing
Container
Swing defines two types of containers.
The first are top-level containers: JFrame, JApplet, JWindow, and Jdialog
These containers do not inherit JComponent. They do, however, inherit the
AWT classes Component and Container. Unlike Swings other components,
which are lightweight, the top-level containers are heavyweight. This makes
the top-level containers a special case in the Swing component library
Must be at the top of a containment hierarchy.
Not contained within any other container.
Most commonly used for applications is JFrame
Container
The second type of containers supported by Swing are lightweight
containers:
Lightweight containers do inherit Jcomponent
An example of a lightweight container - JPanel. which is a general-
purpose container.
Lightweight containers are often used to organize and manage
groups of related components because a lightweight container can be
contained within another container.
Swing Packages
Swing is a very large subsystem and makes use of many
packages.
javax.swing main package
javax.swing.border
javax.swing.colorchooser
javax.swing.event
javax.swing.table
javax.swing.text
javax.swing.tree

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.

For example, clicking on a button, moving the mouse, entering a character


through keyboard, selecting an item from the list, and scrolling the page are the
activities that causes an event to occur.
Event Handling
What is Event Handling?

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

Event class Description


ItemEvent : Generated when a check box or list item is clicked; also
occurs when a choice selection is made or a checkable menu
MouseWheelEvent : Generated when the mouse wheel is moved.
item is selected or deselected.
KeyEvent : Generated when input is received from the keyboard.
MouseEvent: Generated when the mouse is dragged, moved, clicked,
pressed, or released.
TextEvent : Generated when the value of a text area or text field is
changed.
WindowEvent : Generated when a window is activated, closed, deactivated,
opened, or quit.
Event Class Description
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-
clicked, or a menu item is selected.

AdjustmentEvent Generated when a scroll bar is manipulated.

ComponentEvent Generated when a component is hidden, moved, resized, or


becomes visible.

ContainerEvent Generated when a component is added to or removed from a


container.
FocusEvent Generated when a component gains or loses keyboard focus.

InputEvent Abstract superclass for all component input event classes.


Event Listener Interfaces
Interface Description

ActionListener Defines one method to receive action events.


[actionPerformed() ]
public abstract void actionPerformed(ActionEvent e);

AdjustmentListener Defines one method to receive adjustment events.

ComponentListener Defines four methods to recognize when a component is


hidden, moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is
added to or removed from a container.
Event Handling Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo {
JLabel jlab; //Create a new Label
EventDemo()
{ JFrame jfrm = new JFrame("An Event Example");//create a new JFrame container
jfrm.setLayout(new FlowLayout());// specify 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 jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new Jbutton("Beta");
// Add action listener for Alpha
jbtnAlpha.addActionListener (new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jlab.setText("Alpha was pressed."); }
} );
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{ jlab.setText("Beta was pressed."); }
} );
// Add the buttons to the content pane.
jfrm.add(jbtnAlpha); jfrm.add(jbtnBeta);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
jfrm.add(jlab);
//Displaying frame
jfrm.setVisible(true);
}
public static void main(String args[]) {
//object to be created on event dispatching thread than main thread of the application
SwingUtilities.invokeLater(new Runnable()
{ public void run()
{ new EventDemo();
}
}); } }
Anonymous class
It is an inner class without a name.
It should be used if you have to override method of class or interface.
Java Anonymous inner class can be created by two ways:
A. Class (may be abstract or concrete).
B. Interface
Explanation anonymous class
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{ public static void main(String args[])
{
Person p=new Person()
{
void eat(){System.out.println("nice fruits");}
};
p.eat();
} }
Internal working of given code

Person p=new Person(){


void eat(){System.out.println("nice fruits");}
};

A class is created but its name is decided by the compiler


which extends the Person class and provides the
implementation of the eat() method.

An object of Anonymous class is created that is referred


by p reference variable of Person type.
Internal class generated by the compiler

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

public static void main(String class abc implements Runnable


args[]) { { public void run()
{
SwingUtilities.invokeLater (new
Runnable() new SwingDemo();
}
{ public void run()
}
{
Class SwingDemo()
new SwingDemo(); {
} public static void main(String args[])
} {
CLASS
); DEFINITIO
SwingUtilities.invokeLater( new abc);
N }
}
}
Swing Applet
Swing-based applets are similar to AWT-based applets, but with an important
difference
A Swing applet extends JApplet rather than Applet.

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.

setLayout(new FlowLayout()); jbtnBeta.addActionListener new (


// Make two buttons. ActionListener() {
jbtnAlpha = new JButton("Alpha"); public void actionPerformed(ActionEvent le){
jbtnBeta = new JButton("Beta"); jlab.setText("Beta was pressed.");
// Add action listener for Alpha. }
jbtnAlpha.addActionListener (new });
ActionListener() { add(jbtnAlpha); // Add the buttons to the pane.
public void actionPerformed(ActionEvent le) add(jbtnBeta);
{ // Create a text-based label.
jlab.setText("Alpha was pressed."); jlab = new JLabel("Press a button.");
} // Add the label to the content pane.
}); add(jlab);
}}
Explanation
jbtnAlpha.addActionListener (

new ActionListener() { class abc implements ActionListener


public void actionPerformed(ActionEvent
le) {
{ public void actionPerformed(ActionEvent le)
jlab.setText("Alpha was pressed."); {
} jlab.setText("Alpha was pressed.");
}
}
}
); jbtnAlpha.addActionListener ( new abc);
Java JPanel Example

The JPanel is a simplest container class.


It provides space in which an application can attach any other
component.
It inherits the JComponents class.
It doesn't have title bar.

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

Das könnte Ihnen auch gefallen