0% found this document useful (0 votes)
21 views146 pages

Swing

Uploaded by

pdisrocking
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views146 pages

Swing

Uploaded by

pdisrocking
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 146

Swing

• AWT Java AWT (Abstract Window Toolkit) is an API to develop GUI or


window-based applications in java.

• Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system.
• The Java Virtual Machine (JVM) is responsible for translating the AWT calls
into the appropriate calls to the host operating system.

• AWT is heavyweight i.e. its components are using the resources of OS.
• AWT contains numerous classes and methods that allows us to create and
manage windows.

• The main function/purpose of the AWT is to support applet windows, but it can
also be used to create standalone windows.
• The java.awt package provides classes for AWT api such as
• TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

• AWT features include:


• a set of native user interface components
• a robust event-handling model
• graphics and imaging tools, including shape, color, and font classes
• layout managers, for flexible window layouts that don't depend on a
particular window size or screen resolution
Java Swing
• It is a part of Java Foundation Classes (JFC) that is used to create window-based
applications.
• The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
• It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.

• Unlike AWT, Java Swing provides platform-independent and lightweight components.

• The javax.swing package provides classes for java swing API such as
• JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser
etc.
Swing adding rich graphics functionality and interactivity to Java applications.

The Swing components are implemented entirely in the Java programming


language.

Swing supports numerous look and feels, including the ability to create your
own look and feel.
• Features:-
• 1. swings is not a replacement for the AWT needed to support fully architecture
independent interfaces.
• 2. It contains more powerful components.
• 3. It provides with the components, which are not dependent on native source to
sender.
• 4. swings uses the Model-View-Controller (MVC) architecture as the fundamental
design behind each of its components.
• 5. well suited for complex GUI applications.

• Disadvantage:- it is not independent library. It is based on the AWT library.


Partial AWT and Swing
Class Hierarchy java.lang.Object

CheckboxGroup Component MenuComponent

Button Canvas Checkbox Choice Container Label List Scrollbar TextComponent

JComponent Scrollpane Panel Window

AbstractButton JLabel JList JPanel JScrollpane Applet Dialog Frame

JButton JApplet JDialog JFrame

java.awt.* javax.swing.* 14
• JFrame • JCheckBox
• JPanel • JList
• JApplet • JComboBox
• JDialog • JProgressBar
• JLabel • Tool Tips
• JTextField • JSeperator
• JTextArea • JTabbedpane
• JButton • JTree
• JRadioButton • Jtable
• JToggleButton • JScrollPane
Applet
Applet
 An applet is a small program that is intended not to be run on its own, but rather to be
embedded inside another application.
➤ The Applet class must be the superclass of any applet that is to be embedded in a Web page or
viewed by the Java Applet Viewer.

➤ The Applet class provides a standard interface between applets and their environment.
 Applet is java program that can be embedded into HTML pages.

➤ Java applets run on the java enables web browsers such as Mozilla and internet explorer.
➤ Applet is designed to run remotely on the client browser, so there are some restrictions on it.

➤ Applet can't access system resources on the local computer.


➤ Applets are used to make the web site more dynamic and entertaining.
• Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at client
side.

• Advantage of Applet
1. It works at client side so less response time.
2. Secured
3. It can be executed by browsers running under many platforms,
including Linux, Windows, Mac Os etc. Drawback of Applet
1. Plugin is required at client browser to execute applet.
Lifecycle of Java Applet
• Lifecycle of Java Applet
• Applet is initialized.
• Applet is started.
• Applet is painted.
• Applet is stopped.
• Applet is destroyed.

• java.applet.Applet class start()


• For creating any applet java.applet.Applet class must be inherited.
• It provides 4 life cycle methods of applet.
• public void init(): is used to initialized the Applet. It is invoked only once.

• public void start(); is invoked after the init() method or browser is maximized. It is
used to start the Applet.

• public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.

• public void destroy(): is used to destroy the Applet. It is invoked only once.
• Component:- A component is an object having a graphical representation that can be
displayed on the screen and that can interact with the user.

• Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical
user interface.
• The Component class is the abstract superclass of the nonmenu-related Abstract Window
Toolkit components.

• Class Component can also be extended directly to create a lightweight component.

• A lightweight component is a component that is not associated with a native opaque window.
• java.lang.Object
• java.awt.Component

• COMPONENT Direct Known Subclasses: Button, Canvas, Checkbox, Choice, Container,


Label, List, Scrollbar, TextComponent
Some AWT Component Methods

• void setBackground(Color c)
• void setForeground(Color c)
• void setEnabled(boolean b)
• void setVisible(boolean b)
• void setFont(Font f)
• void setSize(Dimension d)
• void setLocation(int x, int y)
All but setSize and setLocation are overridden
by the JComponent class.
Adding Color
The java.awt.Color class has the following static
fields (data members):

• Color.black • Color.magenta
• Color.blue • Color.orange
• Color.cyan • Color.pink
• Color.darkGray • Color.red
• Color.gray • Color.white
• Color.green • Color.yellow
• Color.lightGray
Swing Widgets (more on this next lecture)
Top-Level Containers General-Purpose Containers

JFrame JPanel JScrollPane

JDialog

JSplitPane
JTabbedPane

JButton

JCombobox JList Menu

JCheckbox JRadioButton JLabel


34
and ButtonGroup
More Swing Widgets

JFileChooser

JTree
JTable

JColorChooser 35
Notes on the Code

• Since the frame is a top-level Swing window, components must be


added to its content pane

• When components are added to a container, how they are placed


is dependent upon the container's layout manager

• The default layout manager for a JFrame is a BorderLayout


manager (described later)

• When adding to a container whose layout manager is


BorderLayout, the second parameter should be a location
JPanels

• A JPanel object can be used for grouping components into a


container, which can then be added to another container

• The JPanel constructor with no arguments creates a panel


with a FlowLayout manager

• Another JPanel constructor takes any layout manager as an


argument

• A JPanel can also be used a a blank area for drawing custom


Changing JPanel Layout
JFrame frame = new JFrame("Test Frame");
frame.setSize(new Dimension(300,200));
frame.setLocation(100,100);
Container contentPane = frame.getContentPane();

JLabel label = new JLabel("HERE ARE SOME BUTTONS",


SwingConstants.CENTER);

JButton button1 = new JButton("BUTTON1");


JButton button2 = new JButton("BUTTON2");
JButton button3 = new JButton("BUTTON3");

JPanel panel = new JPanel();


panel.setLayout
(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button1);
panel.add(button2);
panel.add(button3);

contentPane.add(label, BorderLayout.NORTH);
contentPane.add(panel, BorderLayout.CENTER);
New Output

• The button panel is to the west because no other component


was placed there

• The BoxLayout constructor requires both the component


being laid out and either:
• BoxLayout.X_AXIS
• BoxLayout.Y_AXIS
JPanel Example Output

Note use of SwingConstants.CENTER argument


in JLabel constructor.
JPanel Example
JFrame frame = new JFrame("Test Frame");
frame.setSize(new Dimension(300,200));
frame.setLocation(100,100);
Container contentPane = frame.getContentPane();

JLabel label = new JLabel("HERE ARE SOME BUTTONS",


SwingConstants.CENTER);

JButton button1 = new JButton("BUTTON1");


JButton button2 = new JButton("BUTTON2");
JButton button3 = new JButton("BUTTON3");

JPanel panel = new JPanel();


panel.add(button1);
panel.add(button2);
panel.add(button3);

contentPane.add(label, BorderLayout.NORTH);
contentPane.add(panel, BorderLayout.CENTER);

frame.setVisible(true);
Content Panes
• Q: Why not just: frame.setBackground(Color.red); ?
• A: In order to be lightweight, Swing's top-level window objects must
be built on top of a lightweight AWT Container object introduced in
version 1.1
• This container is called a content pane

• Swing top-level window classes:


• JWindow
• JFrame
• JApplet
• JDialog
• JInternalFrame
The Initial Swing GUI
Containment Hierarchy
a 3D model
enables menus
Frame / Dialog / Applet
to pop up above
the content
Root Pane pane
Layered Pane

File Edit

Undo
Redo
Cut

allows for Content Pane


interception of
mouse events
and painting
Glass Pane
across GUI 59
The Initial Swing GUI
Containment Hierarchy
aTopLevelContainer:
JFrame or JDialog or JApplet

rootPane:
JRootPane

(JPanel) glassPane: layeredPane:


java.awt.Component JLayeredPane optional

(JPanel) contentPane: menuBar:


java.awt.Container JMenuBar
60
Layers of JLayeredPane
https://www.educba.com/jlayeredpane/

• Here are some layers of JLayeredPane as explained below in detail:


• DEFAULT_LAYER: This is the standard and bottommost layer, where most components are
inserted.

• PALETTE_LAYER: This layer of JLayeredPanes its over the default layer and useful for
floating toolbars and palettes.

• MODAL_LAYER: This layer of JLayeredPane is used for model dialogs and shown above the
palette layer.

• POPUP_LAYER: This layer of JLayeredPane is used to show popup windows above the modal
layer.

• DRAG_LAYER: A component is shown in this layer (above the popup layer) while dragging it.
When the dragging is finished, the component is shown in its original layer.
• https://www.educba.com/jlayeredpane/
http://www.iitk.ac.in/esc101/05Aug/tutorial/uiswing/components/layeredpane.html
Swing Hello World
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloWorld {


public static void main(String[] args) {
JFrame frame = new JFrame("Hello World!");
frame.setSize(220, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container contentPane = frame.getContentPane();


contentPane.setLayout(null);

JButton button = new JButton("Hello World!");


button.setLocation(30, 30);
button.setSize(150, 100);
contentPane.add(button);

frame.setVisible(true);
}
} 94
Different Kinds of Swing Events
Low-level events
• MouseEvent: Component got mouse-down, mouse-move, etc.
• KeyEvent: Component got key-press, key-release, etc.
• ComponentEvent: Component resized, moved, etc.
• ContainerEvent: Container's contents changed because a component was added or removed
• FocusEvent: Component got focus or lost focus
• WindowEvent: Window opened, closed, etc.

High-level semantic events


• ActionEvent: Main action of control invoked (e.g. JButton click)
• AdjustmentEvent: Value was adjusted (e.g. JScrollBar moved)
• ItemEvent: Item was selected or deselected (e.g. in JList)
• TextEvent: Text in component has changed (e.g in JTextField)
100
Some More Swing Components
That Are JComponents
JComponent

JLayeredPane JPanel

JDesktopPane JScrollPane

JInternalFrame

JTable
JTree
JComboBox

Swing provides a combo box(a combination of a text field and a dropdown list)
through the Jcombobox class,which extends Jcomponent.

A ComboBox normally displays 1 entry

However,it can also display a drop down list that allows user to select a different
entry.

We can also type our selection into the text field.


The JComboBox component,Similar to choice list in AWT,is a combination of TextField and Drop down list of items.

User can make selection by clicking at an item from the list and typing into the box.
Constructors


1) JComboBox()
2) public JComboBox(ComboBoxModel asModel) takes its items from an existing ComboBoxModel.
3) public JComboBox(object[] items) Create a JComboBox that contains the elements of the specified
array

Method:
1)void addItem(Object obj)
• Methods


1)public void setEditable(boolean aFlag) --- It determine JComboBox field is editable or not


2)public Boolean isEditable() -- it returns true if JComboBox is editable. Bydefault Combobox is not
editable


3)public void setMaximumRowCount(int count) -- it sets the maximum no of rows the JComboBox
displays , if the no of object in the model is greater than count the comboBox uses ScrollBar
4)public void setSelectedItem(Object anObject):

5)public void insertItemAt(Object anObject,int index)

6)public void removeItem(Object anObject)

7)public void removeItemAt(int anIndex)


JCheckBox and JSlider
Adding a Check Box and
Slider
public class SwingTest {

public static void main(String[] args) {


JFrame frame = new JFrame("Test Frame");
frame.setSize(new Dimension(400,200));
frame.setLocation(100,100);
Container contentPane = frame.getContentPane();
JLabel label = new JLabel("HERE IS A LABEL");
contentPane.add(label, BorderLayout.NORTH);
JButton button = new JButton("BUTTON");
contentPane.add(button, BorderLayout.SOUTH);

String[] options = {"Option 1", "Option 2", "Option 3"};


JList list = new JList(options);
contentPane.add(list, BorderLayout.CENTER);

JCheckBox cbox = new JCheckBox("Check");


contentPane.add(cbox, BorderLayout.WEST);

JSlider slider = new JSlider();


contentPane.add(slider, BorderLayout.EAST);

frame.setVisible(true);
}
}
New Display
Sizing Hints
• Layout managers often need to resize their components to make things fit
• For example, the widths and heights of components in a BoxLayout are adjusted
according to both preferred and maximum heights and widths

• If you don't like the size of the components a layout manager comes up with, you may
have to give sizing hints using the following methods from the JComponent class:
• void setMinimumSize(Dimension d)
• void setPreferredSize(Dimension d)
• void setMaximumSize(Dimension d)
13.5 TextFields

• JTextField
• Single-line area in which user can enter text

• JPasswordField
• Extends JTextField
• Hides characters that user enters
Thank you

You might also like