Java Swing Tutorial
Java Swing Tutorial
Swing, which is an extension library to the AWT, includes new and improved components that enhance
the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as
Servlets and Applets. It employs a model/view design architecture. Swing is more portable and more
flexible than AWT.
Swing Model/view design: The "view part" of the MV design is implemented with a component object
and the UI object. The "model part" of the MV design is implemented by a model object and a change
listener object.
Swing is built on top of AWT and is entirely written in Java, using AWT's lightweight component
support. In particular, unlike AWT, t he architecture of Swing components makes it easy to customize
both their appearance and behavior. Components from AWT and Swing can be mixed, allowing you to
add Swing support to existing AWT-based programs. For example, swing components such as JSlider,
JButton and JCheckbox could be used in the same program with standard AWT labels, textfields and
scrollbars. You could subclass the existing Swing UI, model, or change listener classes without having to
reinvent the entire implementation. Swing also has the ability to replace these objects on-the-fly.
Three parts
Component set (subclasses of JComponent)
Support classes
Interfaces
In Swing, classes that represent GUI components have names beginning with the letter J. Some examples
are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces in
Swing — twice as many as in AWT.
The class JComponent, descended directly from Container, is the root class for most of Swing's user
interface components.
Swing contains components that you'll use to build a GUI. I am listing you some of the commonly used
Swing components. To learn and understand these swing programs, AWT Programming knowledge is not
required.
Below is a java swing code for the traditional Hello World program.
Basically, the idea behind this Hello World program is to learn how to create a java program, compile
and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or
you can use an IDE like Eclipse.
import javax.swing.JFrame;
import javax.swing.JLabel;
//import statements
//Check if window closes automatically. Otherwise add suitable code
public class HelloWorldFrame extends JFrame {
Output
• JPanel is Swing's version of the AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.
• JFrame is Swing's version of Frame and is descended directly from that class. The
components added to the frame are referred to as its contents; these are managed by the contentPane. To
add a component to a JFrame, we must use its contentPane instead.
• JInternalFrame is confined to a visible area of a container it is placed in. It can be
iconified , maximized and layered.
• JWindow is Swing's version of Window and is descended directly from that class. Like
Window, it uses BorderLayout by default.
• JDialog is Swing's version of Dialog and is descended directly from that class. Like Dialog, it
uses BorderLayout by default. Like JFrame and JWindow,
JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All
dialogs are modal, which means the current
thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis
for creating custom dialogs; however, some
of the most common dialogs are provided through static methods in the class JOptionPane.
• JLabel, descended from JComponent, is used to create text labels.
• The abstract class AbstractButton extends class JComponent and provides a foundation for a
family of button classes, including
JButton.
• JTextField allows editing of a single line of text. New features include the ability to justify
the text left, right, or center, and to set the text's font.
• JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each
character entered can be replaced by an echo character.
This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *.
• JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction
with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or never
have either the vertical or horizontal scrollbar;
JButton is a component the user clicks to trigger a specific action.
• JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of
radio buttons can be associated as a group in which only
one button at a time can be selected.
• JCheckBox is not a member of a checkbox group. A checkbox can be selected and
deselected, and it also displays its current state.
• JComboBox is like a drop down box. You can click a drop-down arrow and select an option
from a list. For example, when the component has focus,
pressing a key that corresponds to the first character in some entry's name selects that entry. A vertical
scrollbar is used for longer lists.
• JList provides a scrollable set of items from which one or more may be selected. JList can be
populated from an Array or Vector. JList does not
support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the
scroll pane can also have a user-defined
border. JList actions are handled using ListSelectionListener.
• JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both
text and an image.
• JToolbar contains a number of components whose type is usually some kind of button which
can also include separators to group related components
within the toolbar.
• FlowLayout when used arranges swing components from left to right until there's no more
space available. Then it begins a new row below it and moves
from left to right again. Each component in a FlowLayout gets as much space as it needs and no more.
• BorderLayout places swing components in the North, South, East, West and center of a
container. You can add horizontal and vertical gaps between
the areas.
• GridLayout is a layout manager that lays out a container's components in a rectangular grid.
The container is divided into equal-sized rectangles,
and one component is placed in each rectangle.
• GridBagLayout is a layout manager that lays out a container's components in a grid of cells
with each component occupying one or more cells,
called its display area. The display area aligns components vertically and horizontally, without requiring
that the components be of the same size.
• JMenubar can contain several JMenu's. Each of the JMenu's can contain a series of
JMenuItem 's that you can select. Swing provides support for
pull-down and popup menus.
• Scrollable JPopupMenu is a scrollable popup menu that can be used whenever we have so
many items in a popup menu that exceeds the screen visible height.
1. Java JFrame class example
JFrame
The components added to the frame are referred to as its contents; these are managed by the contentPane.
To add a component to a JFrame, we must use its contentPane instead.JFrame is a Window with border,
title and buttons. When JFrame is set visible, an event dispatching thread is started. JFrame objects store
several objects including a Container object known as the content pane. To add a component to a JFrame,
add it to the content pane.
JFrame Features
It’s a window with title, border, (optional) menu bar and user-specified components.
It can be moved, resized, iconified.
It is not a subclass of JComponent.
Delegates responsibility of managing user-specified components to a content pane, an instance of JPanel.
Centering JFrame's
By default, a Jframe is displayed in the upper-left corner of the screen. To display a frame
at a specified location, you can use the setLocation(x, y) method in the JFrame class. This
method places the upper-left corner of a frame at location (x, y).
The Swing API keeps improving with abstractions such as the setDefaultCloseOperation method
for the JFrame
Step 3: Set the title of the Jframe to appear in the title bar (title bar will be blank if no title is set).
Step 4: Set the default close operation. When the user clicks the close button, the program stops running.
frame.setLocationRelativeTo( null );
Output
javax.swing
Class JFrame
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Window
java.awt.Frame
javax.swing.JFrame
All Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, RootPaneContainer, Serializable, WindowConstants
JFrame Constructor
JFrame(String title): Creates a new, initially invisible Frame with the specified title.
Java Swing Tutorial Explaining the JInternalFrame class. A JInternalFrame is confined to a visible area of
a container it is placed in. JInternalFrame a top level swing component that has a contentpane.
It can be iconified -- in this case the icon remains in the main application container.
It can be maximized -- Frame consumes the main application
It can be closed using standard popup window controls
It can be layered
import javax.swing.JInternalFrame;
import javax.swing.JDesktopPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JFrame;
import java.awt.event.*;
import java.awt.*;
JDesktopPane jdpDesktop;
static int openFrameCount = 0;
public JInternalFrameDemo() {
super("JInternalFrame Usage Demo");
// Make the main window positioned as 50 pixels from each edge of the
// screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2,
screenSize.height - inset * 2);
// Add a Window Exit Listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Create and Set up the GUI.
jdpDesktop = new JDesktopPane();
// A specialized layered pane to be used with JInternalFrames
createFrame(); // Create first window
setContentPane(jdpDesktop);
setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Frame");
menu.setMnemonic(KeyEvent.VK_N);
JMenuItem menuItem = new JMenuItem("New IFrame");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.addActionListener(new ActionListener() {
Output
JInternalFrame()
Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with no title.
JInternalFrame(String title)
Creates a non-resizable, non-closable, non-maximizable, non-iconifiable JInternalFrame with the specified
title.
Java Swing Tutorial Explaining the JWindow Component. JWindow is Swing's version of Window and is
descended directly from that class. Like Window, it uses BorderLayout by default. Almost all Swing
components are lightweight except JApplet, JFrame, JDialog, and JWindow.
private int X = 0;
private int Y = 0;
public JWindowDemo() {
setBounds(60, 60, 100, 100);
addWindowListener(new WindowAdapter() {
Output
JWindow Constructor
Window(Frame owner)
Constructs a new invisible window with the specified Frame as its owner.
Window(Window owner)
Constructs a new invisible window with the specified Window as its owner.
Java Swing Tutorial Explaining the JLabel Component. JLabel, descended from JComponent, is used to
create text labels.
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.
We use a Swing JLabel when we need a user interface component that displays a message or an image.
JØLabels
Provide text instructions on a GUI
lRead-only text
lPrograms rarely change a label's contents
lClass JLabel (subclass of JComponent)
import java.awt.GridLayout;
Import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
public class JlabelDemo extends JPanel {
Output
JLabel Constructor
JLabel(): Creates a JLabel instance with no image and with an empty string for the title.
Java Swing Tutorial Explaining the JButton Component. The abstract class AbstractButton extends class
JComponent and provides a foundation for a family of button classes, including JButton. A button is a
component the user clicks to trigger a specific action.
There are several types of buttons in Java, all are subclasses of AbstractButton.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.net.URL;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
Output
JFrame jtfMainFrame;
JButton jbnButton1, jbnButton2;
JTextField jtfInput;
JPanel jplPanel;
public JButtonDemo2() {
jtfMainFrame = new JFrame("Which Button Demo");
jtfMainFrame.setSize(50, 50);
jbnButton1 = new JButton("Button 1");
jbnButton2 = new JButton("Button 2");
jtfInput = new JTextField(20);
jplPanel = new JPanel();
jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys
jbnButton1.addActionListener(new ActionListener() {
Output
Java JButton Hierarchy
javax.swing
Class JButton
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.AbstractButton
javax.swing.JButton
All Implemented Interfaces:
Accessible, ImageObserver, ItemSelectable, MenuContainer, Serializable, SwingConstants
Direct Known Subclasses:
BasicArrowButton, MetalComboBoxButton
JButton Constructor
JButton(Action a): Creates a button where properties are taken from the Action supplied.
JButton(String text, Icon icon): Creates a button with initial text and an icon.
Java Swing Tutorial Explaining the JTextField Component. JTextField allows editing/displaying of a
single line of text. New features include the ability to justify the text left, right, or center, and to set the
text's font. 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 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.
JTextField Source Code
//Class Declarations
JTextField jtfText1, jtfUneditableText;
String disp = "";
TextHandler handler = null;
//Constructor
public JTextFieldDemo() {
super("TextField Test Demo");
Container container = getContentPane();
container.setLayout(new FlowLayout());
jtfText1 = new JTextField(10);
jtfUneditableText = new JTextField("Uneditable text field", 20);
jtfUneditableText.setEditable(false);
container.add(jtfText1);
container.add(jtfUneditableText);
handler = new TextHandler();
jtfText1.addActionListener(handler);
jtfUneditableText.addActionListener(handler);
setSize(325, 100);
setVisible(true);
}
//Inner Class TextHandler
private class TextHandler implements ActionListener {
Output
Another Example: JTextField Source Code
public class JTextFieldDemo2 extends JFrame implements ActionListener {
JTextField jtfInput;
JTextArea jtAreaOutput;
String newline = "\n";
public JTextFieldDemo2() {
createGui();
}
public void createGui() {
jtfInput = new JTextField(20);
jtfInput.addActionListener(this);
jtAreaOutput = new JTextArea(5, 20);
jtAreaOutput.setEditable(false);
JScrollPane scrollPane = new JScrollPane(jtAreaOutput,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints gridCons1 = new GridBagConstraints();
gridCons1.gridwidth = GridBagConstraints.REMAINDER;
gridCons1.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(jtfInput, gridCons1);
GridBagConstraints gridCons2 = new GridBagConstraints();
gridCons2.weightx = 1.0;
gridCons2.weighty = 1.0;
contentPane.add(scrollPane, gridCons2);
}
public void actionPerformed(ActionEvent evt) {
String text = jtfInput.getText();
jtAreaOutput.append(text + newline);
jtfInput.selectAll();
}
public static void main(String[] args) {
JTextFieldDemo2 jtfTfDemo = new JTextFieldDemo2();
jtfTfDemo.pack();
jtfTfDemo.addWindowListener(new WindowAdapter() {
JTextField Constructor
JTextField(String text): Constructs a new TextField initialized with the specified text.
JTextField(String text, int columns): Constructs a new TextField initialized with the specified text and
columns.
Java Swing Tutorial Explaining the JPasswordField Component. JPasswordField (a direct subclass of
JTextField) you can suppress the display of input. Each character entered can be replaced by an echo
character. This allows confidential input for passwords, for example. By default, the echo character is the
asterisk, *. 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. If you need to provide an editable text field that doesn’t show the
characters the user types – use the JPasswordField class.
Output
JPasswordField Constructor
JPasswordField()
Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width.
JPasswordField(int columns): Constructs a new empty JPasswordField with the specified number of cols.
JPasswordField(String text)
Constructs a new JPasswordField initialized with the specified text.
Java Swing Tutorial Explaining the JTextArea Component. JTextArea allows editing of multiple lines of
text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying
JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JTextField jtfInput;
JTextArea jtAreaOutput;
String newline = "\n";
public JTextAreaDemo() {
createGui();
}
public void createGui() {
jtfInput = new JTextField(20);
jtfInput.addActionListener(this);
jtAreaOutput = new JTextArea(5, 20);
jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()
.getLength());
jtAreaOutput.setEditable(false);
JScrollPane scrollPane = new JScrollPane(jtAreaOutput,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
GridBagLayout gridBag = new GridBagLayout();
Container contentPane = getContentPane();
contentPane.setLayout(gridBag);
GridBagConstraints gridCons1 = new GridBagConstraints();
gridCons1.gridwidth = GridBagConstraints.REMAINDER;
gridCons1.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(jtfInput, gridCons1);
GridBagConstraints gridCons2 = new GridBagConstraints();
gridCons2.weightx = 1.0;
gridCons2.weighty = 1.0;
contentPane.add(scrollPane, gridCons2);
}
public void actionPerformed(ActionEvent evt) {
String text = jtfInput.getText();
jtAreaOutput.append(text + newline);
jtfInput.selectAll();
}
public static void main(String[] args) {
JTextAreaDemo jtfTfDemo = new JTextAreaDemo();
jtfTfDemo.pack();
jtfTfDemo.addWindowListener(new WindowAdapter() {
Output
JTextArea Constructor
JTextArea(Document doc): Constructs a new JTextArea with the given document model, and defaults for
all of the other arguments (null, 0, 0).
JTextArea(String text): Constructs a new TextArea with the specified text displayed.
JTextArea(String text, int rows, int columns)
Constructs a new TextArea with the specified text and number of rows and columns.
Java Swing Tutorial Explaining the JRadioButton Component. JRadioButton is similar to JCheckbox,
except for the default icon for each class. A set of radio buttons can be associated as a group in which only
one button at a time can be selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Output
JRadioButton Constructor
JRadioButton(): Creates an initially unselected radio button with no set text.
JRadioButton(Action a): Creates a radiobutton where properties are taken from the Action supplied.
JRadioButton(Icon icon): Creates an initially unselected radio button with the specified image but no
text.
JRadioButton(Icon icon, boolean selected): Creates a radio button with the specified image and
selection state, but no text.
JRadioButton(String text): Creates an unselected radio button with the specified text.
JRadioButton(String text, boolean selected): Creates a radio button with the specified text and selection
state.
Java Swing Tutorial Explaining the JCheckBox Component. JCheckBox is not a member of a checkbox
group. A checkbox can be selected and deselected, and it also displays its current state.
JCheckBox Source Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
StringBuffer choices;
JLabel jlbPicture;
CheckBoxListener myListener = null;
public JCheckBoxDemo() {
setLayout(new BorderLayout());
add(jplCheckBox, BorderLayout.WEST);
add(jlbPicture, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
if (e.getStateChange() == ItemEvent.DESELECTED)
c = '-';
choices.setCharAt(index, c);
jlbPicture.setIcon(new ImageIcon("geek-"
+ choices.toString().trim() + ".gif"));
jlbPicture.setToolTipText(choices.toString());
}
}
public static void main(String s[]) {
JFrame frame = new JFrame("JCheckBox Usage Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setContentPane(new JCheckBoxDemo());
frame.pack();
frame.setVisible(true);
}
Output
Java Swing Tutorial Explaining the JComboBox Component. JComboBox is like a drop down box — you
can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when
the component has focus, pressing a key that corresponds to the first character in some entry's name
selects that entry. A vertical scrollbar is used for longer lists.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JLabel jlbPicture;
public JComboBoxDemo() {
String[] comboTypes = { "Numbers", "Alphabets", "Symbols" };
// Create the combo box, and set 2nd item as Default
JComboBox comboTypesList = new JComboBox(comboTypes);
comboTypesList.setSelectedIndex(2);
comboTypesList.addActionListener(new ActionListener() {
Output
Another Example: JComboBox Source Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
import java.text.*;
JComboBox Constructor
JComboBox(): Creates a JComboBox with a default data model.
JComboBox(ComboBoxModel aModel)
Creates a JComboBox that takes it's items from an existing ComboBoxModel.
JComboBox(Object[] items): Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector items): Creates a JComboBox that contains the elements in the specified Vector.
Java Swing Tutorial Explaining the JList Component. JList provides a scrollable set of items from which
one or more may be selected. JList can be populated from an Array or Vector. JList does not support
scrolling directly—instead, the list must be associated with a scrollpane. The view port used by the
scrollpane can also have a user-defined border. JList actions are handled using ListSelectionListener.
JList Source Code
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
JList list;
String[] listColorNames = { "black", "blue", "green", "yellow",
"white" };
Color[] listColorValues = { Color.BLACK, Color.BLUE, Color.GREEN,
Color.YELLOW, Color.WHITE };
Container contentpane;
public JListDemo() {
super("List Source Demo");
contentpane = getContentPane();
contentpane.setLayout(new FlowLayout());
list = new JList(listColorNames);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
contentpane.add(new JScrollPane(list));
list.addListSelectionListener(new ListSelectionListener() {
Output
Java JList Class
javax.swing Class Class JList
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JList
All Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, Scrollable, Serializable
JList Constructor
JList(): Constructs a JList with an empty model.
JList(ListModel dataModel): Constructs a JList that displays the elements in the specified, non-null
model.
JList(Object[] listData): Constructs a JList that displays the elements in the specified array.
JList(Vector listData): Constructs a JList that displays the elements in the specified Vector.
Java Swing Tutorial Explaining the JTabbedPane Component. A JTabbedPane contains a tab that can have
a tool tip and a mnemonic, and it can display both text and an image.
The shape of a tab and the way in which the selected tab is displayed varies by Look and Feel.
Output
JTabbedPane question
When I use a JTabbedPane and want to listen to which tab is being clicked, which listerner should I use?
Answer: ChangeListener
JTabbedPane Constructor
JTabbedPane()
Creates an empty TabbedPane with a default tab placement of JTabbedPane.TOP.
JTabbedPane(int tabPlacement)
Creates an empty TabbedPane with the specified tab placement of either: JTabbedPane.TOP,
JTabbedPane.BOTTOM, JTabbedPane.LEFT, or JTabbedPane.RIGHT.
Java Swing Tutorial Explaining the JToolBar Component. A JToolbar contains a number of components
whose type is usually some kind of button which can also include separators to group related components
within the toolbar. The toolbar can be docked against any of the four edges of a container (panel or a
frame). A toolbar can also be made to float.
Toolbars uses BoxLayout, which arranges components in one horizontal row/ vertical column. This layout
manager does not force each component to have the same height or width; instead, it uses their preferred
height or width, and attempts to align them.
You can adjust the resulting alignment by calling class Component's methods setAlignmentX() and/or
setAlignmentY() on each component.
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
impor t java.awt.*;
import java.awt.event.*;
Output
Java JToolBar Hierarchy
javax.swing
Class JToolBar
java.lang.Object
java.awt.BorderLayout
All Implemented Interfaces:
LayoutManager, LayoutManager2, Serializable
JToolBar Constructor
JToolBar(): Creates a new tool bar; orientation defaults to HORIZONTAL.
JToolBar(int orientation): Creates a new tool bar with the specified orientation.
JToolBar(String name): Creates a new tool bar with the specified name.
JToolBar(String name, int orientation): Creates a new tool bar with a specified name and orientation.
Java Swing Tutorial Explaining the FlowLayout. FlowLayout when used arranges swing components from
left to right until there's no more space available. Then it begins a new row below it and moves from left
to right again. Each component in a FlowLayout gets as much space as it needs and no more.
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
frame.pack();
frame.setVisible(true);
}
Output
Java Swing Tutorial Explaining the BorderLayout . BorderLayout places swing components in the
North, South, East, West and center of a container. All extra space is placed in the center area. You can
add horizontal and vertical gaps between the areas.
Every content pane is initialized to use a BorderLayout. Components are added to a BorderLayout by
using the add method. JFrame’s content pane default layout manager: BorderLayout. In BorderLayout, a
component’s position is specified by a second argument to add.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
if (RIGHT_TO_LEFT) {
contentPane.setComponentOrientation(
java.awt.ComponentOrientation.RIGHT_TO_LEFT);
}
frame.pack();
frame.setVisible(true);
}
output
Java Swing Tutorial Explaining the GridLayout. GridLayout is a layout manager that lays out a container's
components in a rectangular grid. The container is divided into equal-sized rectangles, and one component
is placed in each rectangle.
frame.pack();
frame.setVisible(true);
}
Output
Java GridLayout Hierarchy
javax.swing
Class GridLayout
java.lang.Object
java.awt.GridLayout
All Implemented Interfaces:
LayoutManager, Serializable
GridLayout Constructor
GridLayout(): Creates a grid layout with a default of one column per component, in a single row.
GridLayout(int rows, int cols): Creates a grid layout with the specified number of rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap): Creates a grid layout with the specified number of rows
and columns.
Java Swing Tutorial Explaining the GridBagLayout. GridBagLayout is a layout manager that lays out a
container's components in a grid
of cells with each component occupying one or more cells, called its display area. The display area aligns
components vertically and
horizontally, without requiring that the components be of the same size.
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class GridBagLayoutDemo {
JButton jbnButton;
pane.setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.fill = GridBagConstraints.HORIZONTAL;
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("GridBagLayout Source Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output
GridBagLayout Constructor
GridBagLayout(): Creates a grid bag layout manager..
Java Swing Tutorial Explaining the JMenuBar Component. Swing provides support for pull-down and
popup menus. A JMenubar can contain several JMenu 's. Each of the JMenu 's can contain a series of
JMenuItem 's that you can select.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
JTextArea jtAreaOutput;
JScrollPane jspPane;
public JMenuBar createJMenuBar() {
JMenuBar mainMenuBar;
JMenu menu1, menu2, submenu;
JMenuItem plainTextMenuItem, textIconMenuItem, iconMenuItem, subMenuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
ImageIcon icon = createImageIcon("jmenu.jpg");
mainMenuBar = new JMenuBar();
menu1 = new JMenu("Menu 1");
menu1.setMnemonic(KeyEvent.VK_M);
mainMenuBar.add(menu1);
// Creating the MenuItems
plainTextMenuItem = new JMenuItem("Menu item with Plain Text",
KeyEvent.VK_T);
// can be done either way for assigning shortcuts
// menuItem.setMnemonic(KeyEvent.VK_T);
// Accelerators, offer keyboard shortcuts to bypass navigating the menu
// hierarchy.
plainTextMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK));
plainTextMenuItem.addActionListener(this);
menu1.add(plainTextMenuItem);
textIconMenuItem = new JMenuItem("Menu Item with Text & Image",
icon);
textIconMenuItem.setMnemonic(KeyEvent.VK_B);
textIconMenuItem.addActionListener(this);
menu1.add(textIconMenuItem);
// Menu Item with just an Image
iconMenuItem = new JMenuItem(icon);
iconMenuItem.setMnemonic(KeyEvent.VK_D);
iconMenuItem.addActionListener(this);
menu1.add(iconMenuItem);
menu1.addSeparator();
// Radio Button Menu items follow a seperator
ButtonGroup itemGroup = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem(
"Menu Item with Radio Button");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
itemGroup.add(rbMenuItem);
rbMenuItem.addActionListener(this);
menu1.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem(
"Menu Item 2 with Radio Button");
itemGroup.add(rbMenuItem);
rbMenuItem.addActionListener(this);
menu1.add(rbMenuItem);
menu1.addSeparator();
// Radio Button Menu items follow a seperator
cbMenuItem = new JCheckBoxMenuItem("Menu Item with check box");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
cbMenuItem.addItemListener(this);
menu1.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Menu Item 2 with check box");
cbMenuItem.addItemListener(this);
menu1.add(cbMenuItem);
menu1.addSeparator();
// Sub Menu follows a seperator
submenu = new JMenu("Sub Menu");
submenu.setMnemonic(KeyEvent.VK_S);
subMenuItem = new JMenuItem("Sub MenuItem 1");
subMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
ActionEvent.CTRL_MASK));
subMenuItem.addActionListener(this);
submenu.add(subMenuItem);
subMenuItem = new JMenuItem("Sub MenuItem 2");
submenu.add(subMenuItem);
subMenuItem.addActionListener(this);
menu1.add(submenu);
// Build second menu in the menu bar.
menu2 = new JMenu("Menu 2");
menu2.setMnemonic(KeyEvent.VK_N);
mainMenuBar.add(menu2);
return mainMenuBar;
}
public Container createContentPane() {
// Create the content-pane-to-be.
JPanel jplContentPane = new JPanel(new BorderLayout());
jplContentPane.setLayout(new BorderLayout());// Can do it either way
// to set layout
jplContentPane.setOpaque(true);
// Create a scrolled text area.
jtAreaOutput = new JTextArea(5, 30);
jtAreaOutput.setEditable(false);
jspPane = new JScrollPane(jtAreaOutput);
// Add the text area to the content pane.
jplContentPane.add(jspPane, BorderLayout.CENTER);
return jplContentPane;
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = JMenuDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find image file: " + path);
return null;
}
}
private static void createGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
JFrame frame = new JFrame("JMenu Usage Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuDemo app = new JMenuDemo();
frame.setJMenuBar(app.createJMenuBar());
frame.setContentPane(app.createContentPane());
frame.setSize(500, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem) (e.getSource());
String s = "Menu Item source: " + source.getText()
+ " (an instance of " + getClassName(source) + ")";
jtAreaOutput.append(s + "\n");
jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()
.getLength());
}
public void itemStateChanged(ItemEvent e) {
JMenuItem source = (JMenuItem) (e.getSource());
String s = "Menu Item source: "
+ source.getText()
+ " (an instance of "
+ getClassName(source)
+ ")"
+ "\n"
+ " State of check Box: "
+ ((e.getStateChange() == ItemEvent.SELECTED) ? "selected"
: "unselected");
jtAreaOutput.append(s + "\n");
jtAreaOutput.setCaretPosition(jtAreaOutput.getDocument()
.getLength());
}
// Returns the class name, no package info
protected String getClassName(Object o) {
String classString = o.getClass().getName();
int dotIndex = classString.lastIndexOf(".");
return classString.substring(dotIndex + 1); // Returns only Class name
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
Output