Вы находитесь на странице: 1из 12

Swing:

Java AWT and Java Swing are both part of a group of Java class libraries called the Java Foundation
Classes (JFC). Java AWT is older than Java Swing. At first, Java provided Abstract Windowing
Toolkit (AWT) for GUI interface designing. AWT is based on the underlying native system
components.

The Abstract Windowing Toolkit (AWT) is the original GUI toolkit shipped with the Java
Development Kit (JDK) and Java Swing is built on Java AWT. Few benefits of choosing Java Swings
compared to Java AWT are:

The look and feel and behavior of Java Swing components is consistent across platforms but AWT
components's provides different look and feel and behavior for different platform.
Event model is more efficient in Java Swing as compared to AWT which means Swing components
can run more quickly than their AWT counterparts.

A drawback of Java Swing as compared to Java AWT is that Java Swing components can take longer
to load than AWT components.

Swing features:
Java Swing has many features which makes it ideal for Graphical User Interface (GUI) development.
Few of those are:

 Lightweight: Swing component are independent of native Operating System's API as Swing
API controls are rendered mostly using pure JAVA code instead of underlying operating
system calls.
 Built-in controls like image buttons, tabbed panes, sliders, toolbars, color choosers, tables,
text areas
 Customizable (change border, text alignment, visual appearance of almost any control and
can change)
 Pluggable look and feel
 New features like tool tips, tool bars, keyboard accelerators, custom cursors, etc. are also
available
 Has arbitrary keyboard event binding
 Debugging support is also available

MVC Architecture:
The Model-View-Controller (MVC) architectural pattern is used in software engineering to allow for
the separation of three common features of GUI applications:
 the data access (typically via a database)
 the business logic (how the data will be used)
 user interaction (how the data and actions will be visually presented)
Towards this end one defines three components of such an architecture, the model, view and
controller with the following interactions:
The components are:
 Model: This provides the means by which data is retrieved and manipulated.
 View: This represents the visual interface components of the Graphical User Interface (GUI)
application which interact with the user. The interaction is of an event-driven nature where
actions are initiated via keyboard and mouse.
 Controller: This joins the Model with the View and is the heart of the control logic by
associating user-generated events with data actions.
The interactions correspond to the diagram as follows:
1. All actions begin in the view through events generated by the user. The controller
provides listeners for the events. The controller also has the ability to manipulate the state of
the view objects in a way which offers a response to the events generated by the user.
2. The controller interacts with the model by either requesting information from the data source
based on user-generated events, or by modifying the data based on these events.
3. The model provides the programming interface which the controller must use to access the
database, i.e., the controller does not interact directly with the database. In particular the
notion of "connection" is never seen in the controller. Furthermore, the model also provides
means to avoid, in most cases, direct SQL queries to the database.
4. The view interacts with the model only to know about type information and other data
abstractions held in the model. The relatively weak link indicates that the View/Model
interaction should be "minimal" because the manipulation of data is to be done within the
event handlers of the controller.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

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 & feel. Swing supports pluggable look and feel.
AWT provides less components than Swing. Swing provides more powerful componentssuch 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.
Hierarchy of Java Swing classes

Introduction to Swing Classes

JPanel : JPanel is Swing's version of AWT class Panel and uses the same default layout, FlowLayout.
JPanel is descended directly from JComponent.

JFrame : JFrame is Swing's version of Frame and is descended directly from Frame class. The
component which is added to the Frame, is refered as its Content.

JWindow : This is Swing's version of Window and hass descended directly from Window class.
Like Window it uses BorderLayout by default.

JLabel : JLabel descended from Jcomponent, and is used to create text labels.

JButton : JButton class provides the functioning of push button. JButton allows an icon, string or
both associated with a button.

JTextField : JTextFields allow editing of a single line of text.


Creating a JFrame
There are two way to create a JFrame Window.

1. By instantiating JFrame class.

2. By extending JFrame class.

Example: Creating JFrame window by Instantiating JFrame class


import javax.swing.*;
import java.awt.*;
public class First
{
JFrame jf;
public First()
{
jf = new JFrame("MyWindow");
JButton btn = new JButton("Say Hello");
jf.add(btn);
jf.setLayout(new FlowLayout());
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 400);
jf.setVisible(true);
}
public static void main(String[] args)
{
new First();
}
}
Example2: Creating JFrame window by extending JFrame class
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Second extends JFrame
{
public Second()
{
setTitle("MyWindow");
JLabel lb = new JLabel("Welcome to My Second Window");
add(lb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Second();
}
}
JComboBox class:

The JComboBox class is used to create the combobox (drop-down list). At a time only one item can
be selected from the item list.

Commonly used Constructors of JComboBox class:

 JComboBox()
 JComboBox(Object[] items)
 JComboBox(Vector<?> items)

Commonly used methods of JComboBox class:

1) public void addItem(Object anObject): is used to add an item to the item list.

2) public void removeItem(Object anObject): is used to delete an item to the item list.

3) public void removeAllItems(): is used to remove all the items from the list.

4) public void setEditable(boolean b): is used to determine whether the JComboBox is editable.

5) public void addActionListener(ActionListener a): is used to add the ActionListener.

6) public void addItemListener(ItemListener i): is used to add the ItemListener.

Example:

import javax.swing.*;
public class Combo
{
JFrame f;
Combo()
{
f=new JFrame("Combo ex");

String country[]={"India","Aus","U.S.A","England","Newzeland"};

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 Combo();
}
}

JProgressBar class:

The JProgressBar class is used to display the progress of the task. Commonly used Constructors of
JProgressBar class:

 JProgressBar(): is used to create a horizontal progress bar but no string text.


 JProgressBar(int min, int max): is used to create a horizontal progress bar with the specified
minimum and maximum value.
 JProgressBar(int orient): 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): is used to create a progress bar with the specified
orientation, minimum and maximum value.

Commonly used methods of JProgressBar class:

1) public void setStringPainted(boolean b): is used to determine whether string should be displayed.

2) public void setString(String s): is used to set value to the progress string.

3) public void setOrientation(int orientation): is used to set the orientation, it may be either vertical or
horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants..

4) public void setValue(int value): is used to set the current value on the progress bar.

Example:

import javax.swing.*;
public class MyProgress extends JFrame
{
JProgressBar jb;
int i=0,num=0;

MyProgress()
{
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,200,30);

jb.setValue(0);
jb.setStringPainted(true);

add(jb);
setSize(400,400);
setLayout(null);
}
public void iterate()
{
while(i<=2000)
{
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args)
{
MyProgress m=new MyProgress();
m.setVisible(true);
m.iterate();
}
}

JToolTip:

The Tool Tip is used in conjunction with any Swing component. The Tool Tip is used to give more
in-depth information about a component. An example could be for a JButton. The button may only
display an icon, but a user may not know what that icon means. The user would then place the mouse
over the button in order to view its Tool Tip. The Tool Tip can be a short sentence that explains the
functionality of that button. The Tool Tip can be used to explain functionality or to explain what a
component is displaying to the user.

The easiest way to use a Tool Tip is to utilize the JComponent setToolTipText() method. The
argument for this method is a String which is the text to display. An example using a JButton would
be:

JButton button = new JButton( );


Button.setToolTipText(“The tool tip text”);

This technique can be applied to any JComponent in the Java libraries. Once a JComponent is placed
into your application the text of its Tool Tip can be set.

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

public class JToolTipDemo


{
public static void main(String args[])
{
JFrame f = new JFrame("JToolTip Component");

JButton b=new JButton("show")


{
public JToolTip createToolTip()
{
JToolTip toolTip = super.createToolTip();
toolTip.setBackground(Color.CYAN);
toolTip.setForeground(Color.BLUE);
return toolTip;
}
};

f.add(b,"North");
b.setToolTipText("this is a button");

f.setSize(300, 200);
f.setVisible(true);
}

jSeperator:

The JSeparator class provides a horizontal or vertical dividing line or empty space. It's most
commonly used in menus and tool bars. In fact, you can use separators without even knowing that
a JSeparator class exists, since menus and tool bars provide convenience methods that create and add
separators customized for their containers. Separators are somewhat similar to borders, except that
they are genuine components and, as such, are drawn inside a container, rather than around the edges
of a particular component.

package ajp;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.*;

public class JSeperatorDemo


{
public static void main(String args[])
{
JFrame f = new JFrame("JSeparator Example");
f.setLayout(new GridLayout(0, 1));
JLabel above = new JLabel("Above Separator");
f.add(above);
JSeparator separator = new JSeparator();
f.add(separator);
JLabel below = new JLabel("Below Separator");
f.add(below);
f.setSize(300, 100);
f.setVisible(true);
}
}

JTable class :

The JTable class is used to display the data on two dimensional tables of cells.Commonly used
Constructors of JTable class:
 JTable(): creates a table with empty cells.
 JTable(Object[][] rows, Object[] columns): creates a table with the specified data.

Example of JTable class:

import javax.swing.*;

public class JTableDemo


{
JFrame f;
JTableDemo()
{
f=new JFrame();

String rows[][]={ {"101","Amit","670000"},


{"102","Jai","780000"},
{"101","Sachin","700000"}
};
String columns[]={"ID","NAME","SALARY"};

JTable jt=new JTable(rows,columns);


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 JTableDemo();

}
}

JTrees:

JTree class is used to wrap a tree based control in javax.swing. A tree orders data in a hierarchical
fashion. Sub trees can be expanded and collapsed by the user.

Types of constructors defined by JTree class:

JTree(Hashtable ht) To create a tree with elements of hash table as nodes.


JTree(Object ob[ ]) To create a tree with objects as nodes.
JTree(TreeNode tn) To create a tree with tree node as root of tree.
JTree(Vector v) To create a tree with elements of vector as nodes.
TreePath It is used to translate a mouse click on a point of tree to a tree path. Where,
getPathForLocation( int x and y are coordinates of mouse click.
x ,int y)
DefaultMutableTreeNode class: It is used to represent a node in a tree. Using DefaultMutableTree
Node , you can create nodes for the root and for all of the data you want to represent in the tree.

DefaultMutableTreeNode() creates a node with no associated user object

DefaultMutableTreeNode(Object ob) Creates a node to which you can attach children

DefaultMutableTreeNode(Object To specify that child nodes cannot be attached by supplying


ob,boolean allowschildren) the third argument as false

void add(MutableTreeNode child) It is used to create tree node hierarchy

Example: Procedure to use a tree in Frame:


1) Create a JTree object.
2) Create a JScrollPane object.
3) Add tree to scroll pane.
4) Add scroll pane to content pane of Frame.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class JTreeDemo


{
JTree tree;
JFrame f;

JTreeDemo()
{
f=new JFrame();
f.setLayout(new BorderLayout());

// Create top node of tree


DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");

DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");


top.add(a);
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);

// Create subtree of "A"


DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);

// Create subtree of "B"


DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);

tree = new JTree(top);

JScrollPane jsp = new JScrollPane(tree);


f.add(jsp, BorderLayout.CENTER);

f.setSize(500,500);
f.setVisible(true);
}
public static void main(String args[])
{
JTreeDemo j1=new JTreeDemo();
}
}
Toggle Button

A toggle button is two-states button that allows user to switch on and off. To create a toggle button in
Swing you use JToggleButton class.An implementation of a two-state button. The JRadioButton
and JCheckBox classes are subclasses of this class.

JToggleButton() Creates an initially unselected toggle button


without setting the text or image.
JToggleButton(Action a) Creates a toggle button where properties are
taken from the Action supplied.
JToggleButton(Icon icon) Creates an initially unselected toggle button with
the specified image but no text.
JToggleButton(Icon icon, boolean selected) Creates a toggle button with the specified image
and selection state, but no text.
JToggleButton(String text) Creates an unselected toggle button with the
specified text.
JToggleButton(String text, boolean selected) Creates a toggle button with the specified text
and selection state.
JToggleButton(String text, Icon icon) Creates a toggle button that has the specified text
and image, and that is initially unselected.
JToggleButton(String text, Icon icon, Creates a toggle button with the specified text,
boolean selected) image, and selection state.

import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.*;
public class JToggleDemo
{
public static void main(String[] args)
{

JFrame f = new JFrame("JToggleButton Sample");


JToggleButton b1= new JToggleButton("North");
JButton b2=new JButton("South");
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);

f.setSize(300, 200);
f.setVisible(true);

}
}

Вам также может понравиться