SlideShare une entreprise Scribd logo
1  sur  61
Télécharger pour lire hors ligne
Advanced Java Programming
Lecture 1: Introduction to GUI Programming
By
Ravi Kant Sahu
Asst. Professor
Lovely Professional University, PunjabLovely Professional University, Punjab
Introduction
• AWT is fine for developing simple graphical user interfaces, but
not for developing comprehensive GUI projects.
• Swing components depend less on the target platform and use
less of the native GUI resource.
• Swing GUI component classes are named with a prefixed J.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Why AWT and Swing?
• Although Swing eliminates a number of the limitations inherent
in the AWT, Swing does not replace it.
• Instead, Swing is built on the foundation of the AWT. This is
why the AWT is still a crucial part of Java.
• Swing also uses the same event handling mechanism as the
AWT.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Java Foundation Classes
• JFC encompass a group of features for building graphical user
interfaces (GUIs) and adding rich graphics functionality and
interactivity to Java applications.
 Swing GUI Components
 Pluggable Look-and-Feel Support
 Java 2D API
 Internationalization
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Key Features of Swing
• Swing Components Are Lightweight
Means that they are written entirely in Java and do not map directly to
platform-specific peers.
• Java 2D API
Enables developers to easily incorporate high-quality 2D graphics, text,
and images in applications and applets.
• Internationalization
Allows developers to build applications that can interact with users
worldwide in their own languages and cultural conventions.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Key Features of Swing
• Swing Supports a Pluggable Look and Feel
The look and feel of Swing applications is pluggable, allowing a
choice of look and feel.
• For example, the same program can use either the Java or the Windows
look and feel.
• Additionally, the Java platform supports the GTK+ look and feel, which
makes hundreds of existing look and feels available to Swing programs.
• The Synth package allows you to create your own look and feel.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
AWT Vs Swing
AWT SWING
Components are heavy-weight. Light-weight components.
Native look and feel Pluggable look and feel
Does not have MVC Supports MVC
Not available in AWT. Swing has many advanced features like
JTabel, Jtabbedpane.
Components are platform dependent. Components are platform independent.
AWT components require java.awt
package.
Swing components require javax.swing
package.
Slower Faster than AWT
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Swing API
• GUI API contains classes that can be classified into three
groups: component classes, container classes, and helper
classes.
• The component classes, such as JButton, JLabel, and
JTextField, are for creating the user interface.
• The container classes, such as JFrame, JPanel, and JApplet, are
used to contain other components.
• The helper classes, such as Graphics, Color, Font, FontMetrics,
and Dimension, are used to support GUI components.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Class hierarchy for AWT and Swing
MVC Connection
• A visual component is a composite of three distinct aspects:
1) The state information associated with the component
2) The way that the component looks when rendered on the screen
3) The way that the component reacts to the user
• Model-View-Controller architecture is successful because each piece
of the design corresponds to an aspect of a component.
• By separating a component into a model, a view, and a controller, the
specific implementation of each can be changed without affecting the
other two.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
MVC
• In MVC terminology, the model corresponds to the state information
associated with the component.
• For example, in the case of a check box, the model contains a field
that indicates if the box is checked or unchecked.
• The view determines how the component is displayed on the screen,
including any aspects of the view that are affected by the current state
of the model.
• The controller determines how the component reacts to the user.
For example, when the user clicks a check box, the controller reacts
by changing the model to reflect the user’s choice (checked or
unchecked).
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Swing MVC Architecture
• Swing uses a modified version of MVC that combines the view and
the controller into a single logical entity called the UI delegate.
• For this reason, Swing’s approach is called either the Model Delegate
architecture or the Separable Model architecture.
• Therefore, although Swing’s component architecture is based on
MVC, it does not use a classical implementation of it.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Swing MVC
• Swing’s pluggable look and feel is made possible by its Model-Delegate
architecture.
• Because the view (look) and controller (feel) are separate from the model,
the look and feel can be changed without affecting how the component is
used within a program.
• To support the Model-Delegate architecture, most Swing components
contain two objects.
• The first represents the model and second represents the UI delegate.
• Models are defined by interfaces. For example, the model for a button is
defined by the ButtonModel interface.
• UI delegates are classes that inherit ComponentUI. For example, the UI
delegate for a button is ButtonUI.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Event Dispatching Thread
• Swing programs are event-driven. An event is passed to the
application by calling an event handler defined by the application.
• Swing event handling code runs on a special thread known as the
event dispatch thread.
• Thus, although event handlers are defined by our program, they are
called on a thread that was not created by the program.
• So all Swing GUI components must be created and updated from the
event dispatching thread, not the main thread of the application.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Why EDT?
• Because most Swing object methods are not "thread safe":
invoking them from multiple threads risks thread interference or
memory consistency errors.
• Some Swing component methods are labeled "thread safe" in the
API specification; these can be safely invoked from any thread.
• All other Swing component methods must be invoked from the
event dispatch thread.
• Programs that ignore this rule may function correctly most of the
time, but are subject to unpredictable errors that are difficult to
reproduce.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Event Dispatching Thread
• To enable the GUI code to be created on the event dispatching thread,
we must use one of two methods that are defined by the
SwingUtilities class.
• These methods are invokeLater( ) and invokeAndWait( ).
static void invokeLater (Runnable obj)
static void invokeAndWait(Runnable obj) throws
InterruptedException, InvocationTargetException
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
invokeLater() Vs invokeAndWait()
• invokeLater is used to perform task asynchronously in AWT
Event dispatcher thread while InvokeAndWait is used to
perform task synchronously.
• invokeLater is non blocking call while InvokeAndWait will
block until task is completed.
• invokeLater is more flexible in terms of user interaction because
it just adds the task in Event-Queue and allow user to interact
with system while invokeAndWait is preffered way to update
the GUI from application thread (waits for event to be
completed).
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Swing Containers
• Swing defines two types of containers.
• The first are top-level containers: JFrame, JApplet, JWindow, and
JDialog.
• These containers do not inherit JComponent.
• They do, however, inherit the AWT classes Component and
Container.
• Unlike Swing’s other components, which are lightweight, the top-
level containers are heavyweight.
• This makes the top-level containers a special case in the Swing
component library.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Swing Containers
• The second type of containers supported by Swing are
lightweight containers.
• Lightweight containers (e.g. JPanel, JScrollPane) do inherit
JComponent.
• Lightweight containers are used to organize and manage groups
of related components because a lightweight container can be
contained within another container.
• Thus, we can use lightweight containers to create subgroups of
related controls that are contained within an outer container.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JPanel
• JPanel is a generic lightweight container.
Constructors:
• JPanel()
Creates a new JPanel with a double buffer and a flow layout.
• JPanel(LayoutManager layout)
Create a new buffered JPanel with the specified layout
manager.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JPanel…
Methods:
• PanelUI getUI ()
Returns the look and feel (L&F) object.
• void setUI (PanelUI pi)
Sets the look and feel (L&F) object
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JScrollPane
• JScrollPaneis 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.
• The viewable area of a scroll pane is called theviewport. It is a
window in which the component being scrolled is displayed.
JScrollPane(Component comp)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Steps to create JScrollPane
• Create the component to be scrolled.
• Create an instance of JScrollPane, passing to it the object to scroll.
• Add the scroll pane to the content pane.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JTabbedPane
• It manages a set of components by linking them with tabs.
• The user chooses which component to view by selecting the tab
corresponding to the desired component.
• Selecting a tab causes the component associated with that tab to
come to the forefront.
• If you want similar functionality without the tab interface, you
can use a card layout instead of a tabbed pane.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Constructor:
JTabbedPane()
Adding Tabs:
add() is used to add tabs to the TabbedPane.
void addTab(String name, Component comp)
void addTab(String name, Icon I, Component comp)
Top-Level Container Panes
• Each top-level container defines a set of panes.
• At the top of the hierarchy is an instance of JRootPane.
• JRootPane is a lightweight container whose purpose is to manage the
other panes. It also helps manage the optional menu bar.
• The panes that comprise the root pane are called the glass pane, the
content pane, and the layered pane.
• The glass pane is the top-level pane. It sits above and completely
covers all other panes. By default, it is a transparent instance of
JPanel.
• The layered pane is an instance of JLayeredPane. The layered pane
allows components to be given a depth value. The layered pane holds
the content pane and the (optional) menu bar.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Color class
• We can set colors for GUI components by using the java.awt.Color
class.
• We can use one of the 13 standard colors (BLACK, BLUE, CYAN,
DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE,
PINK, RED, WHITE, and YELLOW) defined as constants in
java.awt.Color.
• Colors are made of red, green, and blue components, each represented
by an int value that describes its intensity, ranging from 0(darkest
shade) to 255(lightest shade). This is known as the RGB model.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• We can create a color using the following constructor:
public Color(int r, int g, int b);
• Color color = new Color(128,100,100);
• The arguments r, g, b are between 0 and 255. If a value beyond this
range is passed to the argument, an IllegalArgumentException will
occur.
Example:
JButton jb1 = new JButton("OK");
jb1.setBackground(color);
jb1.setForeground (new Color(100,1,1));
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Font class
• We can create a font using the java.awt.Font class and set fonts for the
components using the setFont method in the Component class.
• The constructor for Font is:
public Font (String name, int style, int size);
• You can choose a font name from SansSerif, Serif, Monospaced,
Dialog, or DialogInput.
• Choose a style from Font.PLAIN(0), Font.BOLD(1),
Font.ITALIC(2), and Font.BOLD+Font.ITALIC(3), and specify a
font size of any positive integer.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• Example:
Font font1 = new Font("SansSerif", Font.BOLD, 16);
Font font2 = new Font("Serif", Font.BOLD + Font.ITALIC, 12);
JButton jbtOK = new JButton("OK");
jbtOK.setFont(font1);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Setting Default operations in a JFrame
• setDefaultCloseOperation() is used for setting the default operation
for close button of a JFrame.
void setDefaultCloseOperation (int what)
• These constants are declared in WindowConstants, which is an
interface declared in javax.swingthat is implemented by JFrame.
• JFrame.HIDE_ON_CLOSE
• JFrame.DO_NOTHING_ON_CLOSE
• JFrame.EXIT_ON_CLOSE
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Layout Manager classes
LayoutManager class Description
BorderLayout The border layout manager. Border layouts use five
components: North, South, East, West, and Center
CardLayout The card layout manager. Card layouts emulate index
cards. Only the one on top is showing.
GridLayout The grid layout manager. Grid layout displays
components in a two-dimensional grid.
FlowLayout The flow layout manager. Flow layout positions
components left to right, top to bottom.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
FlowLayout
• Arranges the components in left to right, top to bottom fashion.
public FlowLayout ()
public FlowLayout (int alignment)
public FlowLayout (int alignment, int H_Gap, int V_Gap)
• Alignments are specified as:
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
• By default 5 pixels is used as horizontal and vertical gap between
components.
FlowLayout fl = new FlowLayout (FlowLayout.CENTER, 30, 20);
frm.setLayout(fl);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
GridLayout
• It divides a container into a grid of specified rows and columns.
Each to display one component.
• Size of component is changed according to the size of the cell.
public GridLayout (int row, int column)
public GridLayout (int row, int column, int H_Gap, int V_Gap)
GridLayout gl = new GridLayout (3, 4);
frm.setLayout (gl);
GridLayout gl1 = new GridLayout (3, 4, 20, 30);
frm.setLayout (gl2);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
BorderLayout
• It divides the container into 5 regions ( NORTH, SOUTH, EAST,
WEST and CENTER).
• It is the default layout manager for Window.
public BorderLayout()
• To add a component at a specific region, following method is used:
public void add ( Component c, int Region)
Example:
Button btn = new Button(“OK”);
frm.add( btn, BorderLayout.EAST);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
CardLayout
• It is used to arrange containers in the form of deck of cards.
Methods:
first() / last()/ next()/ previous(): is used to make the first/ last/
next/ previous card visible.
show(): is used to make a specified card visible.
public void show ( Container deck, String CardName)
• To give a name to the container while it is added to the deck:
public void add ( Container card, String CardName)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Swing ComponentS
Swing Components
• Swing components are derived from the JComponent class.
• JComponent provides the functionality that is common to all
components.
• For example, JComponent supports the pluggable look and feel.
• JComponent inherits the AWT classes Container and Component.
• Thus, a Swing component is built on and compatible with an AWT
component.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Components
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JLabel
• JLabel is used to display text and/or an icon. It is a passive
component in that it does not respond to user input.
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
• 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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• The icon and text associated with the label can be obtained by the
following methods:
Icon getIcon( )
String getText( )
• The icon and text associated with a label can be set by these
methods:
void setIcon(Icon icon)
void setText(String str)
JTextField
• JTextField allows us to edit one line of text.
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
• The integer argument passed to the JTextField constructor, indicates
the number of columns in the field (Minimum number of characters
displayed in the TextField ‘M’ or ‘W’).
• This number is used along with metrics provided by the field's current
font to calculate the field's preferred width.
• It does not limit the number of characters the user can enter.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JTextArea
• A JTextArea is a multi-line area that displays plain text.
JTextArea ()
JTextArea (String str)
JTextArea (int rows, int cols)
JTextField (String str, int rows, int cols)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JPasswordField
• The JPasswordField class, a subclass of JTextField, provides
specialized text fields for password entry.
JPasswordField pf = new JPasswordField(10);
• For security reasons, a password field does not show the characters
that the user types.
• Instead, the field displays a character different from the one typed,
such as an asterisk ‘*’.
• As another security precaution, a password field stores its value as an
array of characters, rather than as a string.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JPasswordField…
Reading the Password:
char[] input = passwordField.getPassword();
Setting and Getting Echo-char:
void setEchoChar(char)
char getEchoChar()
• void selectAll() method is used to all characters in the password
field.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Swing Buttons
• Swing defines four types of buttons, all are subclasses of the
AbstractButton class, which extends JComponent.
JButton,
JToggleButton,
JCheckBox, and
JRadioButton
• AbstractButton contains many methods:
String getText( )
void setText(String str)
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JButton
• JButton class provides the functionality of a push button.
• JButton allows an icon, a string, or both to be associated with the
push button.
JButton(Icon i)
JButton(String str)
JButton(String str, Icon i)
• When the button is pressed, an ActionEvent is generated.
• We can set the action command by calling setActionCommand( ) on
the button.
• We can obtain the action command by calling getActionCommand( )
on the event object.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JToggleButton
• A toggle button looks just like a push button, but it acts differently
because it has two states: pushed and released.
• Toggle buttons are objects of the JToggleButton class.
• JToggleButton is a super-class for two other Swing components that
also represent two-state controls.
• These are:
JCheckBox and JRadioButton
JToggleButton(String str)
• By default, the button is in the off position.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JCheckBox
• JCheckBox class provides the functionality of a check box.
• Its immediate super class is JToggleButton, which provides support
for two-state buttons.
JCheckBox(String str)
• When the user selects or deselects a check box, an ItemEvent is
generated.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JRadioButton
• Radio buttons are a group of mutually exclusive buttons, in which
only one button can be selected at any one time.
• They are supported by the JRadioButton class, which extends
JToggleButton.
• A button group is created by the ButtonGroup class.
• Its default constructor is invoked for this purpose.
• Elements are added to the button group by using add().
void add(AbstractButton ab)
• JRadioButton generates action events, item events, and change events
each time the button selection changes.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Image Icons
• An icon is a fixed-size picture; typically it is small and used to
decorate components.
• Java supports three image formats: GIF, JPEG, and PNG.
• The image file names for these types end with .gif, .jpg, and .png,
respectively.
• To display an image icon, first create an ImageIcon object using new
javax.swing.ImageIcon(filename).
ImageIcon icon = new ImageIcon (“ravi.jpg");
• An image icon can be displayed in a label or a button using new
JLabel(image-Icon) or new JButton(imageIcon).
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JTable
• JTable is a component that displays rows and columns of data.
• We can drag the cursor on column boundaries to resize columns.
• We 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.
• JTable does not provide any scrolling capabilities of its own. Instead,
we normally wrap a JTable inside a JScrollPane.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JTable(Object data[ ][ ], Object colHeads[ ])
• data is a two-dimensional array of the information to be presented,
and colHeads is a one-dimensional array with the column headings.
• ListSelectionEvent is generated when the user selects something in
the table.
• By default, JTable allows us to select one or more complete rows, but
we can change this behavior to allow one or more columns, or one or
more individual cells to be selected.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Steps to create a JTable
1. Create an instance of JTable.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JList
• It supports the selection of one or more items from a list.
JList(Object [ ] items)
• JListis based on two models.
• The first is ListModel. This interface defines how access to the list
data is achieved.
• The second model is the ListSelectionModel interface, which defines
methods that determine what list item or items are selected.
• A JList generates a ListSelectionEvent when the user makes or
changes a selection.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
• JList allows the user to select multiple ranges of items within the list,
but we can change this behavior by calling setSelectionMode( ),
which is defined by JList.
void setSelectionMode(int mode)
• Here, mode specifies the selection mode. It must be one of these
values defined by
– SINGLE_SELECTION
– SINGLE_INTERVAL_SELECTION
– MULTIPLE_INTERVAL_SELECTION
• The default, multiple-interval selection, lets the user select multiple
ranges of items within a list.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JComboBox
• Combo box 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.
JComboBox(Object[ ]items)
• Items can be dynamically added to the list of choices via the addItem(
) method.
void addItem(Object obj)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JMenu
• A menu provides a space-saving way to let the user choose one of
several options.
• A menu usually appears either in a menu bar or as a popup menu.
• A menu bar contains one or more menus and has a customary,
platform-dependent location, usually along the top of a window.
• A popup menu is a menu that is invisible until the user makes a
platform-specific mouse action, such as pressing the right mouse
button, over a popup-enabled component.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating JMenu
• Create a MenuBar
JMenuBar menuBar = new JMenuBar();
• Create Menus
JMenu menu = new JMenu("File");
• Create MenuItems
JMenuItem mi = new JMenuItem(“Open");
• Add MenuItems to Menu.
menu.add(mi);
• Add Menus to MenuBar
menuBar.add(menu);
• Set the MenuBar to the Container
setJMenuBar(menuBar);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Questions
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

Contenu connexe

Tendances

String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 iimjobs and hirist
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interviewKuntal Bhowmick
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Sagar Verma
 
Core java lessons
Core java lessonsCore java lessons
Core java lessonsvivek shah
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersWhizlabs
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_javaHoang Nguyen
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java BasicsVicter Paul
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
java tutorial for beginner - Free Download
java tutorial for beginner - Free Downloadjava tutorial for beginner - Free Download
java tutorial for beginner - Free DownloadTIB Academy
 

Tendances (17)

String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
Core Java
Core JavaCore Java
Core Java
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
Core java lessons
Core java lessonsCore java lessons
Core java lessons
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed Answers
 
Object oriented programming-with_java
Object oriented programming-with_javaObject oriented programming-with_java
Object oriented programming-with_java
 
Core Java
Core JavaCore Java
Core Java
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
Core java
Core javaCore java
Core java
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
java tutorial for beginner - Free Download
java tutorial for beginner - Free Downloadjava tutorial for beginner - Free Download
java tutorial for beginner - Free Download
 

En vedette (11)

Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Internationalization
InternationalizationInternationalization
Internationalization
 
Jdbc
JdbcJdbc
Jdbc
 
Questions for Class I & II
Questions for Class I & IIQuestions for Class I & II
Questions for Class I & II
 
Servlets
ServletsServlets
Servlets
 
Event handling
Event handlingEvent handling
Event handling
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
List classes
List classesList classes
List classes
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Generics
GenericsGenerics
Generics
 

Similaire à Swing api

Similaire à Swing api (20)

Swing components
Swing components Swing components
Swing components
 
MVP Clean Architecture
MVP Clean  Architecture MVP Clean  Architecture
MVP Clean Architecture
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
Java Training in Chennai
Java Training in Chennai Java Training in Chennai
Java Training in Chennai
 
Gui programming (awt)
Gui programming (awt)Gui programming (awt)
Gui programming (awt)
 
Test automation proposal
Test automation proposalTest automation proposal
Test automation proposal
 
Angular meetup 2 2019-08-29
Angular meetup 2   2019-08-29Angular meetup 2   2019-08-29
Angular meetup 2 2019-08-29
 
java.pptx
java.pptxjava.pptx
java.pptx
 
OOPC_Unit-I.pdf
OOPC_Unit-I.pdfOOPC_Unit-I.pdf
OOPC_Unit-I.pdf
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
 
Professionalizing the Front-end
Professionalizing the Front-endProfessionalizing the Front-end
Professionalizing the Front-end
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Pallavi_Jindal_resume
Pallavi_Jindal_resumePallavi_Jindal_resume
Pallavi_Jindal_resume
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.net
 
Chapter 1-Note.docx
Chapter 1-Note.docxChapter 1-Note.docx
Chapter 1-Note.docx
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-on
 
The 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksThe 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web Frameworks
 

Plus de Ravi_Kant_Sahu

Plus de Ravi_Kant_Sahu (15)

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in Java
 
Event handling
Event handlingEvent handling
Event handling
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Packages
PackagesPackages
Packages
 
Array
ArrayArray
Array
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Inheritance
InheritanceInheritance
Inheritance
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 

Dernier

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

Swing api

  • 1. Advanced Java Programming Lecture 1: Introduction to GUI Programming By Ravi Kant Sahu Asst. Professor Lovely Professional University, PunjabLovely Professional University, Punjab
  • 2. Introduction • AWT is fine for developing simple graphical user interfaces, but not for developing comprehensive GUI projects. • Swing components depend less on the target platform and use less of the native GUI resource. • Swing GUI component classes are named with a prefixed J. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3. Why AWT and Swing? • Although Swing eliminates a number of the limitations inherent in the AWT, Swing does not replace it. • Instead, Swing is built on the foundation of the AWT. This is why the AWT is still a crucial part of Java. • Swing also uses the same event handling mechanism as the AWT. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Java Foundation Classes • JFC encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications.  Swing GUI Components  Pluggable Look-and-Feel Support  Java 2D API  Internationalization Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Key Features of Swing • Swing Components Are Lightweight Means that they are written entirely in Java and do not map directly to platform-specific peers. • Java 2D API Enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and applets. • Internationalization Allows developers to build applications that can interact with users worldwide in their own languages and cultural conventions. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Key Features of Swing • Swing Supports a Pluggable Look and Feel The look and feel of Swing applications is pluggable, allowing a choice of look and feel. • For example, the same program can use either the Java or the Windows look and feel. • Additionally, the Java platform supports the GTK+ look and feel, which makes hundreds of existing look and feels available to Swing programs. • The Synth package allows you to create your own look and feel. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. AWT Vs Swing AWT SWING Components are heavy-weight. Light-weight components. Native look and feel Pluggable look and feel Does not have MVC Supports MVC Not available in AWT. Swing has many advanced features like JTabel, Jtabbedpane. Components are platform dependent. Components are platform independent. AWT components require java.awt package. Swing components require javax.swing package. Slower Faster than AWT Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. Swing API • GUI API contains classes that can be classified into three groups: component classes, container classes, and helper classes. • The component classes, such as JButton, JLabel, and JTextField, are for creating the user interface. • The container classes, such as JFrame, JPanel, and JApplet, are used to contain other components. • The helper classes, such as Graphics, Color, Font, FontMetrics, and Dimension, are used to support GUI components. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. Class hierarchy for AWT and Swing
  • 10. MVC Connection • A visual component is a composite of three distinct aspects: 1) The state information associated with the component 2) The way that the component looks when rendered on the screen 3) The way that the component reacts to the user • Model-View-Controller architecture is successful because each piece of the design corresponds to an aspect of a component. • By separating a component into a model, a view, and a controller, the specific implementation of each can be changed without affecting the other two. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. MVC • In MVC terminology, the model corresponds to the state information associated with the component. • For example, in the case of a check box, the model contains a field that indicates if the box is checked or unchecked. • The view determines how the component is displayed on the screen, including any aspects of the view that are affected by the current state of the model. • The controller determines how the component reacts to the user. For example, when the user clicks a check box, the controller reacts by changing the model to reflect the user’s choice (checked or unchecked). Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. Swing MVC Architecture • Swing uses a modified version of MVC that combines the view and the controller into a single logical entity called the UI delegate. • For this reason, Swing’s approach is called either the Model Delegate architecture or the Separable Model architecture. • Therefore, although Swing’s component architecture is based on MVC, it does not use a classical implementation of it. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. Swing MVC • Swing’s pluggable look and feel is made possible by its Model-Delegate architecture. • Because the view (look) and controller (feel) are separate from the model, the look and feel can be changed without affecting how the component is used within a program. • To support the Model-Delegate architecture, most Swing components contain two objects. • The first represents the model and second represents the UI delegate. • Models are defined by interfaces. For example, the model for a button is defined by the ButtonModel interface. • UI delegates are classes that inherit ComponentUI. For example, the UI delegate for a button is ButtonUI. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. Event Dispatching Thread • Swing programs are event-driven. An event is passed to the application by calling an event handler defined by the application. • Swing event handling code runs on a special thread known as the event dispatch thread. • Thus, although event handlers are defined by our program, they are called on a thread that was not created by the program. • So all Swing GUI components must be created and updated from the event dispatching thread, not the main thread of the application. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. Why EDT? • Because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. • Some Swing component methods are labeled "thread safe" in the API specification; these can be safely invoked from any thread. • All other Swing component methods must be invoked from the event dispatch thread. • Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. Event Dispatching Thread • To enable the GUI code to be created on the event dispatching thread, we must use one of two methods that are defined by the SwingUtilities class. • These methods are invokeLater( ) and invokeAndWait( ). static void invokeLater (Runnable obj) static void invokeAndWait(Runnable obj) throws InterruptedException, InvocationTargetException Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. invokeLater() Vs invokeAndWait() • invokeLater is used to perform task asynchronously in AWT Event dispatcher thread while InvokeAndWait is used to perform task synchronously. • invokeLater is non blocking call while InvokeAndWait will block until task is completed. • invokeLater is more flexible in terms of user interaction because it just adds the task in Event-Queue and allow user to interact with system while invokeAndWait is preffered way to update the GUI from application thread (waits for event to be completed). Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. Swing Containers • Swing defines two types of containers. • The first are top-level containers: JFrame, JApplet, JWindow, and JDialog. • These containers do not inherit JComponent. • They do, however, inherit the AWT classes Component and Container. • Unlike Swing’s other components, which are lightweight, the top- level containers are heavyweight. • This makes the top-level containers a special case in the Swing component library. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. Swing Containers • The second type of containers supported by Swing are lightweight containers. • Lightweight containers (e.g. JPanel, JScrollPane) do inherit JComponent. • Lightweight containers are used to organize and manage groups of related components because a lightweight container can be contained within another container. • Thus, we can use lightweight containers to create subgroups of related controls that are contained within an outer container. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. JPanel • JPanel is a generic lightweight container. Constructors: • JPanel() Creates a new JPanel with a double buffer and a flow layout. • JPanel(LayoutManager layout) Create a new buffered JPanel with the specified layout manager. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. JPanel… Methods: • PanelUI getUI () Returns the look and feel (L&F) object. • void setUI (PanelUI pi) Sets the look and feel (L&F) object Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. JScrollPane • JScrollPaneis 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. • The viewable area of a scroll pane is called theviewport. It is a window in which the component being scrolled is displayed. JScrollPane(Component comp) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. Steps to create JScrollPane • Create the component to be scrolled. • Create an instance of JScrollPane, passing to it the object to scroll. • Add the scroll pane to the content pane. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. JTabbedPane • It manages a set of components by linking them with tabs. • The user chooses which component to view by selecting the tab corresponding to the desired component. • Selecting a tab causes the component associated with that tab to come to the forefront. • If you want similar functionality without the tab interface, you can use a card layout instead of a tabbed pane. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. Constructor: JTabbedPane() Adding Tabs: add() is used to add tabs to the TabbedPane. void addTab(String name, Component comp) void addTab(String name, Icon I, Component comp)
  • 26. Top-Level Container Panes • Each top-level container defines a set of panes. • At the top of the hierarchy is an instance of JRootPane. • JRootPane is a lightweight container whose purpose is to manage the other panes. It also helps manage the optional menu bar. • The panes that comprise the root pane are called the glass pane, the content pane, and the layered pane. • The glass pane is the top-level pane. It sits above and completely covers all other panes. By default, it is a transparent instance of JPanel. • The layered pane is an instance of JLayeredPane. The layered pane allows components to be given a depth value. The layered pane holds the content pane and the (optional) menu bar. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 27. Color class • We can set colors for GUI components by using the java.awt.Color class. • We can use one of the 13 standard colors (BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, and YELLOW) defined as constants in java.awt.Color. • Colors are made of red, green, and blue components, each represented by an int value that describes its intensity, ranging from 0(darkest shade) to 255(lightest shade). This is known as the RGB model. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. • We can create a color using the following constructor: public Color(int r, int g, int b); • Color color = new Color(128,100,100); • The arguments r, g, b are between 0 and 255. If a value beyond this range is passed to the argument, an IllegalArgumentException will occur. Example: JButton jb1 = new JButton("OK"); jb1.setBackground(color); jb1.setForeground (new Color(100,1,1)); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29. Font class • We can create a font using the java.awt.Font class and set fonts for the components using the setFont method in the Component class. • The constructor for Font is: public Font (String name, int style, int size); • You can choose a font name from SansSerif, Serif, Monospaced, Dialog, or DialogInput. • Choose a style from Font.PLAIN(0), Font.BOLD(1), Font.ITALIC(2), and Font.BOLD+Font.ITALIC(3), and specify a font size of any positive integer. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. • Example: Font font1 = new Font("SansSerif", Font.BOLD, 16); Font font2 = new Font("Serif", Font.BOLD + Font.ITALIC, 12); JButton jbtOK = new JButton("OK"); jbtOK.setFont(font1); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 31. Setting Default operations in a JFrame • setDefaultCloseOperation() is used for setting the default operation for close button of a JFrame. void setDefaultCloseOperation (int what) • These constants are declared in WindowConstants, which is an interface declared in javax.swingthat is implemented by JFrame. • JFrame.HIDE_ON_CLOSE • JFrame.DO_NOTHING_ON_CLOSE • JFrame.EXIT_ON_CLOSE Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 32. Layout Manager classes LayoutManager class Description BorderLayout The border layout manager. Border layouts use five components: North, South, East, West, and Center CardLayout The card layout manager. Card layouts emulate index cards. Only the one on top is showing. GridLayout The grid layout manager. Grid layout displays components in a two-dimensional grid. FlowLayout The flow layout manager. Flow layout positions components left to right, top to bottom. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 33. FlowLayout • Arranges the components in left to right, top to bottom fashion. public FlowLayout () public FlowLayout (int alignment) public FlowLayout (int alignment, int H_Gap, int V_Gap) • Alignments are specified as: FlowLayout.LEFT FlowLayout.RIGHT FlowLayout.CENTER • By default 5 pixels is used as horizontal and vertical gap between components. FlowLayout fl = new FlowLayout (FlowLayout.CENTER, 30, 20); frm.setLayout(fl); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 34. GridLayout • It divides a container into a grid of specified rows and columns. Each to display one component. • Size of component is changed according to the size of the cell. public GridLayout (int row, int column) public GridLayout (int row, int column, int H_Gap, int V_Gap) GridLayout gl = new GridLayout (3, 4); frm.setLayout (gl); GridLayout gl1 = new GridLayout (3, 4, 20, 30); frm.setLayout (gl2); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 35. BorderLayout • It divides the container into 5 regions ( NORTH, SOUTH, EAST, WEST and CENTER). • It is the default layout manager for Window. public BorderLayout() • To add a component at a specific region, following method is used: public void add ( Component c, int Region) Example: Button btn = new Button(“OK”); frm.add( btn, BorderLayout.EAST); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 36. CardLayout • It is used to arrange containers in the form of deck of cards. Methods: first() / last()/ next()/ previous(): is used to make the first/ last/ next/ previous card visible. show(): is used to make a specified card visible. public void show ( Container deck, String CardName) • To give a name to the container while it is added to the deck: public void add ( Container card, String CardName) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 38. Swing Components • Swing components are derived from the JComponent class. • JComponent provides the functionality that is common to all components. • For example, JComponent supports the pluggable look and feel. • JComponent inherits the AWT classes Container and Component. • Thus, a Swing component is built on and compatible with an AWT component. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 39. Components Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 40. JLabel • JLabel is used to display text and/or an icon. It is a passive component in that it does not respond to user input. JLabel(Icon icon) JLabel(String str) JLabel(String str, Icon icon, int align) • 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 41. • The icon and text associated with the label can be obtained by the following methods: Icon getIcon( ) String getText( ) • The icon and text associated with a label can be set by these methods: void setIcon(Icon icon) void setText(String str)
  • 42. JTextField • JTextField allows us to edit one line of text. JTextField(int cols) JTextField(String str, int cols) JTextField(String str) • The integer argument passed to the JTextField constructor, indicates the number of columns in the field (Minimum number of characters displayed in the TextField ‘M’ or ‘W’). • This number is used along with metrics provided by the field's current font to calculate the field's preferred width. • It does not limit the number of characters the user can enter. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 43. JTextArea • A JTextArea is a multi-line area that displays plain text. JTextArea () JTextArea (String str) JTextArea (int rows, int cols) JTextField (String str, int rows, int cols) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 44. JPasswordField • The JPasswordField class, a subclass of JTextField, provides specialized text fields for password entry. JPasswordField pf = new JPasswordField(10); • For security reasons, a password field does not show the characters that the user types. • Instead, the field displays a character different from the one typed, such as an asterisk ‘*’. • As another security precaution, a password field stores its value as an array of characters, rather than as a string. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 45. JPasswordField… Reading the Password: char[] input = passwordField.getPassword(); Setting and Getting Echo-char: void setEchoChar(char) char getEchoChar() • void selectAll() method is used to all characters in the password field. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 46. Swing Buttons • Swing defines four types of buttons, all are subclasses of the AbstractButton class, which extends JComponent. JButton, JToggleButton, JCheckBox, and JRadioButton • AbstractButton contains many methods: String getText( ) void setText(String str) void setDisabledIcon(Icon di) void setPressedIcon(Icon pi) void setSelectedIcon(Icon si) void setRolloverIcon(Icon ri) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 47. JButton • JButton class provides the functionality of a push button. • JButton allows an icon, a string, or both to be associated with the push button. JButton(Icon i) JButton(String str) JButton(String str, Icon i) • When the button is pressed, an ActionEvent is generated. • We can set the action command by calling setActionCommand( ) on the button. • We can obtain the action command by calling getActionCommand( ) on the event object. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 48. JToggleButton • A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. • Toggle buttons are objects of the JToggleButton class. • JToggleButton is a super-class for two other Swing components that also represent two-state controls. • These are: JCheckBox and JRadioButton JToggleButton(String str) • By default, the button is in the off position. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 49. JCheckBox • JCheckBox class provides the functionality of a check box. • Its immediate super class is JToggleButton, which provides support for two-state buttons. JCheckBox(String str) • When the user selects or deselects a check box, an ItemEvent is generated. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 50. JRadioButton • Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time. • They are supported by the JRadioButton class, which extends JToggleButton. • A button group is created by the ButtonGroup class. • Its default constructor is invoked for this purpose. • Elements are added to the button group by using add(). void add(AbstractButton ab) • JRadioButton generates action events, item events, and change events each time the button selection changes. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 51. Image Icons • An icon is a fixed-size picture; typically it is small and used to decorate components. • Java supports three image formats: GIF, JPEG, and PNG. • The image file names for these types end with .gif, .jpg, and .png, respectively. • To display an image icon, first create an ImageIcon object using new javax.swing.ImageIcon(filename). ImageIcon icon = new ImageIcon (“ravi.jpg"); • An image icon can be displayed in a label or a button using new JLabel(image-Icon) or new JButton(imageIcon). Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 52. JTable • JTable is a component that displays rows and columns of data. • We can drag the cursor on column boundaries to resize columns. • We 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. • JTable does not provide any scrolling capabilities of its own. Instead, we normally wrap a JTable inside a JScrollPane. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 53. JTable(Object data[ ][ ], Object colHeads[ ]) • data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings. • ListSelectionEvent is generated when the user selects something in the table. • By default, JTable allows us to select one or more complete rows, but we can change this behavior to allow one or more columns, or one or more individual cells to be selected. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 54. Steps to create a JTable 1. Create an instance of JTable. 2. Create a JScrollPane object, specifying the table as the object to scroll. 3. Add the table to the scroll pane. 4. Add the scroll pane to the content pane. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 55. JList • It supports the selection of one or more items from a list. JList(Object [ ] items) • JListis based on two models. • The first is ListModel. This interface defines how access to the list data is achieved. • The second model is the ListSelectionModel interface, which defines methods that determine what list item or items are selected. • A JList generates a ListSelectionEvent when the user makes or changes a selection. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 56. • JList allows the user to select multiple ranges of items within the list, but we can change this behavior by calling setSelectionMode( ), which is defined by JList. void setSelectionMode(int mode) • Here, mode specifies the selection mode. It must be one of these values defined by – SINGLE_SELECTION – SINGLE_INTERVAL_SELECTION – MULTIPLE_INTERVAL_SELECTION • The default, multiple-interval selection, lets the user select multiple ranges of items within a list. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 57. JComboBox • Combo box 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. JComboBox(Object[ ]items) • Items can be dynamically added to the list of choices via the addItem( ) method. void addItem(Object obj) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 58. JMenu • A menu provides a space-saving way to let the user choose one of several options. • A menu usually appears either in a menu bar or as a popup menu. • A menu bar contains one or more menus and has a customary, platform-dependent location, usually along the top of a window. • A popup menu is a menu that is invisible until the user makes a platform-specific mouse action, such as pressing the right mouse button, over a popup-enabled component. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 59. Creating JMenu • Create a MenuBar JMenuBar menuBar = new JMenuBar(); • Create Menus JMenu menu = new JMenu("File"); • Create MenuItems JMenuItem mi = new JMenuItem(“Open"); • Add MenuItems to Menu. menu.add(mi); • Add Menus to MenuBar menuBar.add(menu); • Set the MenuBar to the Container setJMenuBar(menuBar); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 61. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)