Beruflich Dokumente
Kultur Dokumente
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 4:
Swings
4.1 Basics
AWT translates its various visual components into their corresponding, platform-specific equivalents, or peers. Therefore, the look and
feel will be decided by the platform and not by Java. Therefore, AWT is referred to as heavyweight. This led to following problems
Definition
Swing API is set of extensible GUI Components to ease developer's life to create JAVA based Front End/ GUI Applications. It is built on
top of AWT API and it overcomes most of its limitations. Swing has almost every control corresponding to AWT controls.
AWT Swing
AWT components are platform-dependent Swing are platform independent
AWT is called the abstract window tool Swing is part of the java foundation classes
AWT components are heavyweight components Swing components are lightweight components because
swing sits on the top of AWT
AWT occupies more memory space Swing occupies less memory space
AWT require javax.awt package Swing requires javax.swing package
AWT is not MVC based Swing are MVC based architecture
AWT works slower Swing works faster
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.
Swing based GUI Application’s look and feel logic can be separated from the component’s business
logic.
It is possible to define look and feel that is consistent across all platforms.
Conversely, it is also possible to create a look and feel that acts like a specific platform.
It is also possible to create a custom look and feel.
Look and feel can be changed dynamically at runtime.
Rich controls
Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls
Highly Customizable
Swing controls can be customized in very easy way as visual appearance is independent of internal representation
Components
Containers
A container holds a group of components. Thus, container is a special type of component that is designed to
hold other components.
There are two types of containers
Top level containers (JFrame, JApplet, JWindow, and JDialog):
These containers do not inherit the JComponent. They do directly inherit the AWT classes
Component and Container. Therefore, they are heavyweight.
They cannot be contained within any other component.
Those who inherit JComponent are the second type of container:
They are lightweight
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.parser
javax.swing.text.rtf
javax.swing.tree
javax.swing.undo
import javax.swing.*;
class Example
{
Example()
{
// Create a new JFrame container.
JFrame frame = new JFrame("My first Swing Application");
new Example();
}
}
Output
Basics
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as 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 list, scrolling the page are the activities that causes an event to happen.
Foreground events: These events require the direct interaction of the user. Example: Click on a button
Background events: These don’t require the interaction of the user. Example: OS interrupt.
As we learnt in unit 3, delegation event model has the following key participants namely:
public Example()
statusLabel.setSize(350, 100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
Output
In order to design a listener class we have to develop some listener interfaces. These Listener interfaces forecast some public abstract
callback methods which must be implemented by the listener class.
If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.
Concept
Swing-based applets are similar to AWT-based applets, but it 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.
Swing applets use the same four lifecycle methods as described in unit 2: init(), start(), stop(), and destroy()
Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally override the paint() method.
Example:
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 Example extends JApplet
{
JButton button1;
JButton button2;
JLabel label;
Output
Let’s discuss some of the lightweight components derived from JComponent class.
Description
A JLabel object provides text instructions or information on a GUI — display a single line of read-only text, an image or both text and
image.
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here,
str and icon are the text and icon used for the label.
The align argument specifies the horizontal alignment of the text and/or icon within the dimensions of
the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING.
these constants are defined in the SwingConstants interface, along with several others used by the
Swing classes.
The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and encapsulates an image. Thus, an
object of type ImageIcon can be passed as an argument to the Icon parameter of JLabel’s constructor
Example:
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
public void init()
{
render();
// Create a label.
JLabel label = new JLabel("This is a sample message", imgIcon, JLabel.LEFT);
Output
4.9 JTextField
Description
JTextField is an input area where the user can type in characters. If you want to let the user enter multiple lines of text, you cannot
use JTextField’s unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines
of text.
When the user types data into them and presses the Enter key, an action event occurs. If the program registers an event listener, the
listener processes the event and can use the data in the text field at the time of the event in the program
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
Here,
str is the string to be initially presented, and
If no string is specified, the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the specified
string.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
JTextField textfield;
textfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
// Show text when user presses ENTER.
showStatus(textfield.getText());
}
});
}
}
Output
The text associated with the button can be read and written via the following methods
String getText()
void setText(String str)
A button generates an action event when it is pressed. Other events are also possible.
JButton
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be associated with
the push button. When the button is pressed, an ActionEvent is generated and it is handled by the actionPerformed()
method of registered ActionListener
It defines three constructors
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button
Example:
import java.awt.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class Example extends JApplet implements ActionListener
{
JLabel label;
Output
JToggleButton
A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. That is,
when you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you
press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed; it toggles
between its two states. It generates an ItemEvent.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
JToggleButton toggleButton;
Output
JCheckBox
The JCheckBox class provides the functionality of a check box. When the user selects or deselects a check box, an
ItemEvent is generated.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet implements ItemListener
{
JLabel label;
cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
// Create the label and add it to the content pane.
label = new JLabel("Select languages");
add(label);
}
Output
JRadioButton
Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time.
Example
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet implements ActionListener
{
JLabel label;
Output
4.11 JTabbedPane
Description
A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image.
Example:
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
public void init()
{
render();
}
@SuppressWarnings("serial")
class Sem2 extends JPanel
{
public Sem2()
{
JButton b1 = new JButton("Mathematics 2");
add(b1);
JButton b2 = new JButton("Civil");
add(b2);
JButton b3 = new JButton("Basic Electricals");
add(b3);
JButton b4 = new JButton("Physics");
add(b4);
}
}
Output
4.12 JScrollPane
Description
JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled
can either be an individual component, such as a table, or a group of components contained within another lightweight container, such
as a JPanel. In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are
automatically provided, and the component can be scrolled through the pane. Because JScrollPane automates scrolling, it usually
eliminates the need to manage individual scroll bars
Example
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
public void init()
{
render();
}
Output
4.13 JList
Description
Example
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
JList<Object> list;
JLabel label;
JScrollPane scrollpane;
Output
4.14 JComboBox
Description
JComboBox is a combination of a text field and a drop-down list. A combo box normally displays one entry, but it will also display a drop-
down list that allows a user to select a different entry.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
@SuppressWarnings("serial")
public class Example extends JApplet
{
JLabel label;
JComboBox<Object> comboBox;
String flags[] = { "aklc", "jmaster" };
// Handle selections.
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
String s = (String) comboBox.getSelectedItem();
label.setIcon(new ImageIcon(s + ".png"));
}
});
Output
4.15 JTable
JTable is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You
can also drag a column to a new position. Depending on its configuration, it is also possible to select a row, column, or cell within the
table, and to change the data within a cell.
Example
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
@SuppressWarnings("serial")
public class Example extends JApplet
{
public void init()
{
render();
}
Output