Swings Tutorial 1
Swings Tutorial 1
Prakash Gyamlani
(MCA, DAC, ‘A’ Level)
Senior Software Engineer
AmpliFlex Softwares (P) Ltd
Swings Tutorial 1
What is Java Swing?
Swings Tutorial 2
What is Java Swing …Contd
Following Figure represents only a small fraction of the Swing library, but this fraction consists of the
classes you will be dealing with most. The rest of Swing exists to provide extensive support and
customization capabilities for the components these classes define.
Swings Tutorial 3
Swing API
The Java Swing provides the multiple platform independent
APIs interfaces for interacting between the users and GUIs
components. All Java Swing classes imports form the import
javax.swing.*; package. Java provides interactive features for
design the GUIs toolkit or components like: labels, buttons,
text boxes, checkboxes, combo boxes, panels and sliders etc.
All AWT flexible components can be handled by the Java
Swing. The Java Swing supports the plugging between the look
and feel features. The look and feel that means the
dramatically changing in the component like JFrame, JWindow,
JDialog etc. for viewing it into the several types of window.
Swings Tutorial 4
AWT V/s Swing
Z- order
Swing components are referred to as lightweights while AWT components
are referred to as heavyweights. The difference between lightweight and
heavyweight components is z-order: the notion of depth or layering. Each
heavyweight component occupies its own z-order layer. All lightweight
components are contained inside heavyweight components and maintain
their own layering scheme defined by Swing. When we place a heavyweight
inside another heavyweight container it will, by definition, overlap all
lightweights in that container.
What this ultimately means is that we should avoid using both heavyweight
and lightweight components in the same container whenever possible. This
does not mean that we can never mix AWT and Swing components
successfully. It just means we have to be careful and know which situations
are safe and which are not. Since we probably won't be able to completely
eliminate the use of heavyweight components anytime soon, we have to
find ways to make the two technologies work together in an acceptable way.
The most important rule to follow is that we should never place heavyweight
components inside lightweight containers that commonly support
overlapping children. Some examples of these containers are
JInternalFrame, JScrollPane, JLayeredPane, and JDesktopPane.
Swings Tutorial 5
AWT V/s Swing Contd…
2 Platform independence
The most remarkable thing about Swing
components is that they are written in 100% Java
and do not depend on peer components, as most
AWT components do. This means that a Swing
button or text area will look and function identically
on Macintosh, Solaris, Linux, and Windows
platforms. This design eliminates the need to test
and debug applications on each target platform.
Swings Tutorial 6
MVC architecture
MVC is a well known object-oriented user interface
design Components are broken down into three parts: a
model, a view, and a controller. Each Swing component
is based on a more modern version of this design.
Before we discuss how MVC works in Swing, we need to
understand how it was originally designed to work.
Swings Tutorial 7
Model
Swings Tutorial 8
View
Swings Tutorial 9
Controller
Swings Tutorial 10
MVC Relation
Swings Tutorial 11
Swing package overview
javax.swing
Contains the most basic Swing components, default component models, and
interfaces. (Most of the classes shown in Figure 1.2 are contained in this
package.)
javax.swing.border
Classes and interfaces used to define specific border styles. Note that
borders can be shared by any number of Swing components, as they are
not components themselves.
javax.swing.colorchooser
Classes and interfaces supporting the JColorChooser component, used for
color selection. (This package also contains some interesting undocumented
private classes.)
javax.swing.event
The event package contains all Swing-specific event types and listeners.
Swing components also support events and listeners defined in
java.awt.event and java.beans.
javax.swing.filechooser
Classes and interfaces supporting the JFileChooser component, used for file
selection.
Swings Tutorial 12
Swing package overview…Contd
javax.swing.plaf
Contains the pluggable look-and-feel API used to define custom user interface
components. Most of the classes in this package are abstract. They are subclassed and
implemented by look-and-feel implementations such as metal, motif, and basic. The
classes in this package are intended for use only by developers who, for one reason or
another, cannot build on top of existing look-and-feels.
javax.swing.plaf.basic
Consists of the Basic look-and-feel implementation which all look-and-feels provided
with Swing are built on top of. We are normally expected to subclass the classes in this
package if we want to create our own customized look-and-feel.
javax.swing.plaf.metal
Metal is the default look-and-feel of Swing components. It is the only look-and-feel that
ships with Swing not designed to be consistent with a specific platform
javax.swing.plaf.multi
This is the Multiplexing look-and-feel. This is not a regular look-and-feel implementation
in that it does not define the actual look or feel of any components. Rather, it provides
the ability to combine several look-and-feels for simultanteous use. A typical example
might be using an audio-based look-and-feel in combination with metal or motif.
Currently Java 2 does not ship with any multiplexing look-and-feel implemenations
(however, rumor has it that the Swing team is working on an audio look-and-feel as we
write this).
Swings Tutorial 13
Swing package overview…Contd
javax.swing.table
Classes and interfaces supporting the JTable control. This component is used to manage
tabular data in spreadsheet form. It supports a high degree of customization without
requiring look-and-feel enhancements.
javax.swing.text
Classes and interfaces used by the text components including support for plain and
styled documents, the views of those documents, highlighting, caret control and
customization, editor actions and keyboard customization.
javax.swing.text.html
This extension of the text package contains support for HTML text components. (HTML
support was being completely rewritten and expanded upon while we were writing this
book. Because of this our coverage of it is regretably limited.)
javax.swing.text.html.parser
Support for parsing HTML.
javax.swing.text.rtf
Contains support for RTF documents.
javax.swing.tree
Classes and interfaces supporting the JTree component. This component is used for the
display and management of hierarcical data. It supports a high degree of customization
without requiring look-and-feel enhancements.
javax.swing.undo
The undo package contains support for implementing and managing undo/redo
functionality.
Swings Tutorial 14
Simple components that are used primarily to get
input from the user; they may also show simple state
JButton
JComboBox
JCheckBox
JList
Swings Tutorial 15
Simple components that are used primarily to get input from
the user; they may also show simple stat …Contd
JMenu
JRadioButton
JSlider
Swings Tutorial 16
Simple components that are used primarily to get input from
the user; they may also show simple stat …Contd
JSlider
JTextField
Swings Tutorial 17
These components display highly formatted information that
(if you choose) can be modified by the user.
JColorChooser
JFileChooser
Swings Tutorial 18
These components display highly formatted information that
(if you choose) can be modified by the user. … continued
JTable
JTextArea
Swings Tutorial 19
Un-editable Information Displays These components
exist solely to give the user information
JLabel
JProgressBar
JSeparator
JToolTip
Swings Tutorial 20
Top-Level Containers At least one of these components
must be present in any Swing application
JApplet
JDialog
JFrame
Swings Tutorial 21
General-Purpose Containers
These general-purpose containers are used in most
Swing applications.
JPanel
JSplitPane
JTabbedPane
Swings Tutorial 22
General-Purpose Containers
These general-purpose containers are used in most
Swing applications … Continued
JScrollPane
JToolBar
Swings Tutorial 23
Special-Purpose Containers
These special-purpose containers play specific roles in the
UI.
JInternalFrame
Swings Tutorial 24
Event Handling
What is the event?
That is an event!
Swings Tutorial 25
Event Handling in Java
In life, you encounter events that force you to
suspend other activities and respond to them
immediately. In Java, events represent all activity
that goes on between the user and the application.
Java’s Abstract Windowing Toolkit (AWT)
communicates these actions to the programs using
events. When the user interacts with a program let us
say by clicking a command button, the system creates
an event representing the action and delegates it to
the event-handling code within the program. This
code determines how to handle the event so the user
gets the appropriate response.
Swings Tutorial 26
Components of an Event
Can be put under the following categories.
1. Event Object: When the user interacts with the application by clicking a
mouse button or pressing a key an event is generated. The Operating
System traps this event and the data associated with it. For example, info
about time at which the event occurred, the event types (like keypress or
mouse click). This data is then passed on to the application to which the
event belongs. In Java, events are represented by objects, which describe
the events themselves. And Java has a number of classes that describe and
handle different categories of events.
2. Event Source: An event source is the object that generated the event.
Example if you click a button an ActionEvent Object is generated. The object
of the ActionEvent class contains information about the event.
3. Event-Handler: Is a method that understands the event and processes
it. The event-handler method takes the Event object as a parameter. Java
uses Event-Delegation Model :with JDK1.1 onwards; you can specify the
objects that are to be notified when a specific event occurs. If the event is
irrelevant, it is discarded. The four main components based on this model
are Event classes, Event Listeners, Explicit event handling and
Adapters. Let us take a closer look at them one by one.
Swings Tutorial 27
Event Classes
Swings Tutorial 28
Semantic events
Semantic events are defined at a higher-level to encapsulate the
semantics of user interface component’s model. Now let us see
what are the various semantic event classes and what they
generate:
• An ActionEvent object is generated when a component is
activated
• An AdjustmentEvent Object is generated when scrollbars and
other adjustment elements are used.
• A TextEvent object is generated when text of a component is
modified.
• An ItemEvent is generated when an item from a list, a choice or
checkbox is selected.
Swings Tutorial 29
Low-Level Events
Low-Level Events is one that represents a low-level input or windows-system occurrence on
a visual component on the screen. The various low-level event classes and what they
generate are as follows:
• A ContainerEvent Object is generated when component are added or removed from
container.
• A ComponentEvent object is generated when a component is resized, moved etc.
• A FocusEvent object is generated when component receives focus for input.
• A KeyEvent object is generated when key on keyboard is pressed, released etc.
• A WindowEvent object is generated when a window activity, like maximizing or close
occurs.
• A MouseEvent object is generated when a mouse is used.
• A PaintEvent object is generated when component is painted.
Swings Tutorial 30
Event Listeners
Event Listeners: An object delegates the task of handling an
event to an event listener. When an event occurs, an event
object of the appropriate type (as illustrated below) is created.
This object is passed to a Listener. A listener must implement
the interface that has the method for event handling. A
component can have multiple listeners, and a listener can be
removed using removeActionListener () method. Next question in
your mind must be what is an interface?.
An Interface contains constant values and method declaration.
The difference between classes and interface is that the methods
in an interface are only declared and not implemented, that is,
the methods do not have a body. What is the Need for interface?
Are interfaces are used to define behavior protocols (standard
behavior) that can be implemented by any class anywhere in the
class hierarchy. The java.awt.event package contains definitions
of all event classes and listener interface
Swings Tutorial 31
Listeners …Contd
The semantic listener interfaces define
by AWT for the above mentioned semantic
events are:
• ActionListener
• AjdustmentListener
• ItemListener
• TextListener
Swings Tutorial 32
Listeners …Contd
The low-level event listeners are as follows:
• ComponentListener
• ContainerListener
• FocusListener
• KeyListener
• MouseListener
• MouseMotionListener
• WindowsListener
Swings Tutorial 33
Swing Examples
Swing in Action
Swings Tutorial 34
Example 1
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonDemo extends JPanel implements ActionListener {
protected JButton b1, b2, b3;
public ButtonDemo() {
// Create Icons for Buttons
ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
ImageIcon rightButtonIcon = createImageIcon("images/left.gif");
b1 = new JButton("Disable middle button", leftButtonIcon);
Swings Tutorial 35
Example 1 …Contd
b1.setVerticalTextPosition(AbstractButton.CENTER);// Default Center
b1.setHorizontalTextPosition(AbstractButton.LEADING); // Default Right
// locales
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
b2 = new JButton("Middle button", middleButtonIcon);
b2.setVerticalTextPosition(AbstractButton.BOTTOM);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M);
b3 = new JButton("Enable middle button", rightButtonIcon);
// Use the default text position of CENTER, TRAILING (RIGHT).
b3.setMnemonic(KeyEvent.VK_E);
b3.setActionCommand("enable");
b3.setEnabled(false);
// Listen for actions on buttons 1 and 3.
b1.addActionListener(this);
b3.addActionListener(this);
b1.setToolTipText("Click this button to disable the middle button.");
b2.setToolTipText("This middle button does nothing when you click it.");
b3.setToolTipText("Click this button to enable the middle button.");
Swings Tutorial 36
Example 1 …Contd
// Add Components to this
container, using the default
FlowLayout.
add(b1);
add(b2);
add(b3);
}
Swings Tutorial 37
Example 1 …Contd
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
Swings Tutorial 38
Example 1 …Contd
Swings Tutorial 39
Example 1 …Contd
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
System.out.println("In Create and Show GUI");
// Create and set up the window.
JFrame frame = new JFrame("ButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
ButtonDemo newContentPane = new ButtonDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// frame.add(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
Swings Tutorial 40
Example 1 …Contd
public static void
main(String[] args)
throws Exception {
// creating and
showing this application's
GUI.
createAndShowGUI();
}
}
Swings Tutorial 41
Example 2 of JButton
package mypack;
import java.awt.FlowLayout;
Import javax.swing.*;
import javax.swing.plaf.basic.BasicArrowButton
public class Buttons extends JApplet {
private JButton jb = new JButton("JButton");
private BasicArrowButton up = new
BasicArrowButton(BasicArrowButton.NORTH),
down = new BasicArrowButton(BasicArrowButton.SOUTH),
right = new BasicArrowButton(BasicArrowButton.EAST),
left = new BasicArrowButton(BasicArrowButton.WEST);
Swings Tutorial 42
Example 2 of JButton …Contd
public void init() {
// Container cp = getContentPane();
setLayout(new FlowLayout());
add(jb);
add(new JToggleButton("JToggleButton"));
add(new JCheckBox("JCheckBox"));
add(new JRadioButton("JRadioButton"));
JPanel jp = new JPanel();
jp.setBorder(new TitledBorder("Directions"));
jp.add(up);
jp.add(down);
jp.add(left);
jp.add(right);
add(jp);
}
Swings Tutorial 44
Simple Example of JTree
package mypack;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class SimpleTree extends JFrame {
public static void main(String[] args) {
new SimpleTree();
}
public SimpleTree() {
super("Creating a Simple JTree");
// WindowUtilities.setNativeLookAndFeel();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = getContentPane();
Swings Tutorial 45
Simple Example of JTree …Contd
Object[] hierarchy = {
"javax.swing",
"javax.swing.border",
"javax.swing.colorchooser",
"javax.swing.event",
"javax.swing.filechooser",
new Object[] { "javax.swing.plaf",
"javax.swing.plaf.basic",
"javax.swing.plaf.metal",
"javax.swing.plaf.multi" },
"javax.swing.table",
new Object[] {
"javax.swing.text",
new Object[] {
"javax.swing.text.html",
"javax.swing.text.html.parser" },
"javax.swing.text.rtf" },
"javax.swing.tree",
"javax.swing.undo" };
Swings Tutorial 46
Simple Example of JTree …Contd
DefaultMutableTreeNode root = processHierarchy(hierarchy);
JTree tree = new JTree(root);
content.add(new JScrollPane(tree), BorderLayout.CENTER);
setSize(275, 300);
setVisible(true);
}
Swings Tutorial 47
Simple Example of JTree …Contd
private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
DefaultMutableTreeNode node = new
DefaultMutableTreeNode(hierarchy[0]);
DefaultMutableTreeNode child;
for (int i = 1; i < hierarchy.length; i++) {
Object nodeSpecifier = hierarchy[i];
if (nodeSpecifier instanceof Object[]) // Ie node with children
child = processHierarchy((Object[]) nodeSpecifier);
else
child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
node.add(child);
}
return (node);
}
}
Swings Tutorial 48
Output of Example 2
Swings Tutorial 49
Example of JTree with Look and
Feel
Swings Tutorial 50
Code of JTree Example with Diff.
Look and Feel
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
Swings Tutorial 51
Code of JTree Example with Diff.
Look and Feel … Contd
private JTree tree;
private JTextField currentSelectionField;
public SelectableTree() {
super("JTree Selections");
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.Win
dowsLookAndFeel"); // Windows Look and Feel
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.Motif
LookAndFeel");//Motif Look and Feel
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println("Could not load LookAndFeel");
}
Swings Tutorial 52
Code of JTree Example with Diff.
Look and Feel … Contd
……………………….
……………
tree.addTreeSelectionListener(this); //Registering Event
………..
currentSelectionField = new JTextField("Current Selection: NONE");
……
public void valueChanged(TreeSelectionEvent event) {
currentSelectionField.setText("Current Selection: "
+
tree.getLastSelectedPathComponent().toString());
}
Swings Tutorial 53
JSpinner Demo Example
Swings Tutorial 54
JSpinner Example Code
import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerListModel;
public class SpinnerDemo extends JFrame {
// Create a number spinner
SpinnerDemo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createSpinner();
pack();
setVisible(true);
}
Swings Tutorial 55
JSpinner Example Code … Contd
public void createSpinner() {
// Set its value
setLayout(new BorderLayout());
JSpinner spinner = new JSpinner();
spinner.setValue(new Integer(100));
JSpinner spinner1 = new JSpinner();
SpinnerListModel listModel = new SpinnerListModel(new String[] { "red",
"green", "blue" });
spinner1 = new JSpinner(listModel);
// Set its value
spinner1.setValue("blue");
JSpinner spinner2 = new JSpinner();
SpinnerDateModel dateModel = new SpinnerDateModel();
Swings Tutorial 56
JSpinner Example Code … Contd
public static void main(String args[]) {
new SpinnerDemo();
}
…………………..
Swings Tutorial 57
More for JSpinner
Listening for Changes to the Value in a JSpinner
Component
// Create a nummber spinner
JSpinner spinner = new JSpinner();
// Add the listener
spinner.addChangeListener(new SpinnerListener());
// Changing the value programmatically also fires an event
spinner.setValue(new Integer(100));
public class SpinnerListener implements ChangeListener {
public void stateChanged(ChangeEvent evt)
{ JSpinner spinner = (JSpinner)evt.getSource();
// Get the new value
Object value = spinner.getValue(); } }
Swings Tutorial 58
JProgressBar
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
public class ProgressBarDemo extends JFrame {
ProgressBarDemo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
createBar();
pack();
setVisible(true);
}
public static void main(String args[]) {
new ProgressBarDemo();
}
Swings Tutorial 59
ProgressBar … Contd
public void createBar() {
// Create a horizontal progress bar
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(minimum, maximum);
add(progress,BorderLayout.NORTH);
// Create a vertical progress bar
JProgressBar progressV = new JProgressBar(minimum, maximum);
minimum = 0;
maximum = 100;
progressV = new JProgressBar(JProgressBar.VERTICAL, minimum,
maximum);
//progressV.setStringPainted(true);
add(progressV,BorderLayout.EAST);
Swings Tutorial 60
ProgressBar … Contd
// Get the current value
int value = progress.getValue();
// Set the value; the new value will be forced into the bar's range
int newValue = 150;
progress.setValue(newValue);
Swings Tutorial 61
Menu Example
………….
………
//Create Menu
//When the user selects a menu item, it fires an action event.
// Create the menu bar
JMenuBar menuBar = new JMenuBar();
// Create a menu
JMenu menu = new JMenu("Menu Label"); menuBar.add(menu);
Swings Tutorial 63
Tab Pane Example
………………….
……………..
// Create a child container which is to be associated with a tab
JPanel panel = new JPanel();
// Add components to the panel...
// Create the tabbed pane
JTabbedPane pane = new JTabbedPane(); // Add a tab
String label = "Tab Label"; pane.addTab(label, panel);
……………………
……………
Swings Tutorial 64
Tab Pane Example
…………………
………….
Enabling and Disabling a Tab in a JTabbedPane Container
By default, all new tabs are enabled, which means the user can select them. A
tab can be disabled to prevent the user from selecting it.
// Create a tabbed pane
JTabbedPane pane = new JTabbedPane();
// Add a tab
pane.addTab("Tab Label", component);
// Get index of the new tab
int index = pane.getTabCount()-1;
// Determine whether the tab is enabled
boolean enabled = pane.isEnabledAt(index);
// Disable the tab
pane.setEnabledAt(index, false);
………………….
…………
Swings Tutorial 65
JDesktopPane Example
Creating a JDesktopPane Container
A desktop is a container that can only hold internal frames
(JInternalFrame objects). This example creates a desktop with an
internal frame.
// Create an internal frame
boolean resizable = true;
boolean closeable = true;
boolean maximizable = true;
boolean iconifiable = true;
String title = "Frame Title";
JInternalFrame iframe = new JInternalFrame(title, resizable, closeable,
maximizable, iconifiable);
// Set an initial size
int width = 200;
int height = 50;
iframe.setSize(width, height);
// By default, internal frames are not visible; make it visible
iframe.setVisible(true);
Swings Tutorial 66
JDesktopPane Example …Contd
// Add components to internal frame...
iframe.getContentPane().add(new JTextArea());
// Add internal frame to desktop
JDesktopPane desktop = new JDesktopPane();
desktop.add(iframe);
// Display the desktop in a top-level frame
JFrame frame = new JFrame();
frame.getContentPane().add(desktop, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
Swings Tutorial 67
Getting All Frames in a
JDesktopPane Container
// Retrieve all internal frames
JInternalFrame[] frames = desktop.getAllFrames();
for (int i=0; i<frames.length; i++) {
// Get internal frame's title
String title = frames[i].getTitle();
// Determine if the internal frame is visible
boolean isVisible = frames[i].isVisible();
// Get other properties
boolean isCloseable = frames[i].isClosable();
boolean isResizeable = frames[i].isResizable();
boolean isIcon = frames[i].isIcon();
boolean isMaximizable = frames[i].isMaximizable();
boolean isSelected = frames[i].isSelected();
}
Swings Tutorial 68
Enable / Disable all Tool Tip Text
We can stop or active functionality of Tool tip by single
function:
Swings Tutorial 69
Layout Examples
public class BoxDemo extends JFrame {
BoxDemo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
createGUI();
pack();
setVisible(true);
}
public void createGUI() {
// Here is a another way to create a horizontal box container
Box box = new Box(BoxLayout.X_AXIS);
box = Box.createHorizontalBox();
// Here is a another way to create a horizontal box container
Box box1 = new Box(BoxLayout.Y_AXIS);
box1 = Box.createVerticalBox();
// Add components
box.add(new JButton("Button1"));
box.add(new JButton("Button2"));
box1.add(new JButton("Button1"));
box1.add(new JButton("Button2"));
add(box,BorderLayout.EAST);
add(box1,BorderLayout.WEST);
}
public static void main(String[] args) {
new BoxDemo();
}
}
Swings Tutorial 70
Laying Out Components
Laying Out Components in a Flow (Left-to-Right, Top-to-Bottom)
int align = FlowLayout.CENTER; // or LEFT, RIGHT JPanel panel = new
JPanel(new FlowLayout(align)); panel.add(component1);
panel.add(component2);
Swings Tutorial 71
AbstractAction Example
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ActionDemo extends JFrame {
public Action action = new AbstractAction("Action Name") {
// This is an instance initializer; it is executed just after the constructor of the
superclass is invoked
{
// The following values are completely optional
// Set tool tip text
putValue(Action.SHORT_DESCRIPTION, "Tool Tip Text");
// Set an icon
Icon icon = new ImageIcon("icon.gif");
putValue(Action.SMALL_ICON, icon);
// Set a mnemonic character. In most look and feels, this causes the
// specified character to be underlined This indicates that if the
putValue(Action.MNEMONIC_KEY, new Integer(
java.awt.event.KeyEvent.VK_A));
}
// This method is called when the action is invoked
public void actionPerformed(ActionEvent evt) {
JOptionPane.showConfirmDialog(null, "Hello");
}
}; Swings Tutorial 72
Summary
What is Swing?
AWT Vs Swing
Swing MVC Architecture
Event Handling
Components of Event
Examples
Swings Tutorial 73
Thanks & Regards
Prakash Gyamlani
Swings Tutorial 74