Java Unit 1
Java Unit 1
GUI programming
What is GUI?
● A GUI, or Graphical User Interface, is a type of user interface that allows people to
interact with a computer or device through visual elements like windows, icons, buttons,
and menus, rather than through text commands.
● For example, when you use a computer, clicking on icons, opening files by
double-clicking them, or navigating through a software application using menus and
buttons are all parts of a GUI.
● It makes it easier for users to operate software by providing a visual and intuitive way to
interact with the device.
Abstract Window Toolkit (AWT)
● AWT, or Abstract Window Toolkit, is a set of tools in the Java programming language
used to create graphical user interfaces (GUIs).
● It provides a way to build windows, buttons, text fields, and other components for Java
applications.
Problems with AWT
1. Heavyweight
2. Platform Dependency:
3. Limited Components
4. Less Flexibility (Look and Feel)
Introduction
● Swing is a part of Java's standard library for building graphical user interfaces (GUIs).
● It is built on top of AWT but offers more advanced and flexible components.
● Swing provides a richer set of GUI components, such as buttons, text fields, tables, trees,
and more, which are designed to look consistent across different operating systems.
● 1990s: In the mid-1990s, Sun Microsystems recognized the need for a modern,
platform-independent GUI toolkit for Java. They aimed to create a more sophisticated
GUI toolkit than the earlier AWT (Abstract Window Toolkit).
● 1997: Swing was introduced as part of the Java Foundation Classes (JFC) in
JDK 1.2 (Java 2). It provided a more flexible and customizable set of
components compared to AWT. Swing aimed to provide a consistent look and
feel across different platforms.
● Early 2000s: Swing became widely adopted by Java developers for building
desktop applications, as it offered a rich set of components and features.
Two Key Features of Swing
1. Pluggable Look and Feel
Swing's pluggable look and feel feature allows developers to change the appearance and
behavior of their application's GUI components without altering the application's code. This
means you can switch between different "skins" or styles for your application, making it
adaptable to various user preferences or system themes.
2. Lightweight Components
Swing components are lightweight, meaning they are written entirely in Java and do not rely
on native operating system components. This makes Swing components more flexible and
easier to manage, as they are not tied to the underlying platform's GUI system.
Advantages of Swing
Top-Level Containers
Dialogs
1. JOptionPane: Provides standard dialog boxes such as message, confirm, and input
dialogs.
2. JFileChooser: A dialog that allows users to choose files or directories.
3. JColorChooser: A dialog that allows users to choose a color.
First Program
import javax.swing.JFrame;
public class Example1 {
public Example1() {
JFrame f=new JFrame("GUI");
f.setSize(300, 330);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(3);
f.setVisible(true);
}
public static void main(String[] args) {
new Example1();
}
}
Second Program
import javax.swing.JFrame;
public class Example2 extends JFrame {
public Example2() {
setTitle("Example 2");
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setVisible(true);
}
}
}
JLabel and ImageIcon
● JLabel can be used to display text and/or an icon. It is a passive component in that it
does not respond to user input.
● JLabel defines several constructors. Here are three of them:
○ 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.
● The easiest way to obtain an icon is to use the ImageIcon class.
● ImageIcon implements Icon and encapsulates an image.
● Thus, an object of type ImageIcon can be passed as an argument to the Icon
parameter of JLabel’s constructor.
● There are several ways to provide the image, including reading it from a file or
downloading it from a URL.
● Here is the ImageIcon constructor used by the example in this section:
● ImageIcon(String filename)
● It obtains the image in the file named filename.
● 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)
● Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it is
possible to change the text inside a label during program execution.
import javax.swing.*;
class SwingDemo{
public SwingDemo(){
JFrame f=new JFrame("Swing Demo");
f.setSize(400,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
○ JTextField(int cols)
○ JTextField(String str)
● Here, str is the string to be initially presented, and cols is the number of columns in the
text field. If no string is specified, the text field is initially empty. If the number of columns
is not specified, the text field is sized to fit the specified string.
○ JButton(Icon icon)
○ JButton(String str)
● Here, str and icon are the string and icon used for the button.
● A toggle button looks just like a push button, but it acts differently because it has two
states: pushed and released.
● JToggleButton(String str)
● Like JButton, JToggleButton generates an action event each time it is pressed. Unlike
JButton, however, JToggleButton also generates an item event.
● The easiest way to determine a toggle button’s state is by calling the isSelected( )
method on the button that generated the event. It is shown here:
● boolean isSelected( )
● It returns true if the button is selected and false otherwise.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JToggleButtonDemo {
public JToggleButtonDemo(){
JFrame frame = new JFrame(“JToggleButton Demo");
frame.setSize(200, 200);
frame.setLayout(new FlowLayout());
JLabel l1=new JLabel("Button is off");
JToggleButton jtbtn=new JToggleButton("on/off");
jtbtn.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if( jtbtn.isSelected()){
l1.setText("button is on");
}else{
l1.setText("button is off");
}
}
});
frame.add( jtbtn);
frame.add(l1);
frame.setVisible(true);
}
public static void main(String[] args) {
new JToggleButtonDemo();
}
}
Check Boxes
● The JCheckBox class provides the functionality of a check box.
● JCheckBox defines several constructors. The one used here is
● JCheckBox(String str)
● It creates a check box that has the text specified by str as a label.
● When the user selects or deselects a check box, an ItemEvent is generated. You can
obtain a reference to the JCheckBox that generated the event by calling getItem( ) on
the ItemEvent passed to the itemStateChanged( ) method defined by ItemListener.
● The easiest way to determine the selected state of a check box is to call isSelected( ) on
the JCheckBox instance.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public JCheckBoxDemo2() {
JFrame frame = new JFrame("Checkbox Demo");
frame.setLayout(new GridLayout(2, 1));
frame.setSize(600, 400);
JPanel p = new JPanel(new FlowLayout());
JPanel p1 = new JPanel(new FlowLayout());
c1 = new JCheckBox("singing");
c2 = new JCheckBox("dancing");
● Most often, it is the action event that is handled, which means that you will normally
implement the ActionListener interface.
JComboBox
● Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class.
● 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.
● You can also create a combo box that lets the user enter a selection into the text field.
● In the past, the items in a JComboBox were represented as Object references.
However, beginning with JDK 7, JComboBox was made generic and is now declared
like this: class JComboBox<E>
● Here, E represents the type of the items in the combo box. The JComboBox
constructor used by the example is shown here:
● JComboBox(E[ ] items)
● Here, items is an array that initializes the combo box.
● In addition to passing an array of items to be displayed in the drop-down list, items can be
dynamically added to the list of choices via the addItem( ) method, shown here:
● JComboBox generates an action event when the user selects an item from the list.
● JComboBox also generates an item event when the state of selection changes, which
occurs when an item is selected or deselected.
● Thus, changing a selection means that two item events will occur: one for the deselected
item and another for the selected item.
● One way to obtain the item selected in the list is to call getSelectedItem( ) on the combo
box. It is shown here:
● Object getSelectedItem( )
● You will need to cast the returned value into the type of object stored in the list
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
}
Layout Managers
● Layout managers in Java are used to control the size and position of components within
a container.
● They provide a level of abstraction over the manual positioning and sizing of
components, allowing developers to create complex and dynamic user interfaces
without having to deal with pixel-level details.
● Types
○ FlowLayout Manager
○ GridLayout Manager
○ BorderLayout Manager
○ CardLayout Manager
○ GridBagLayout Manager
FlowLayout
● Arranges components in a left-to-right flow, much like lines of text in a paragraph. When
one line is full, it moves to the next line.
● It is used for simple dialogs and panels where components should be laid out in a row.
panel.setLayout(new FlowLayout());
BorderLayout
● Divides the container into five regions: North, South, East, West, and Center. Each
region can contain only one component.
frame.setLayout(new BorderLayout());
● A flexible and complex layout manager that aligns components vertically and
horizontally, without requiring that the components be of the same size.
● It is used in complex forms and applications where components need to span multiple
rows or columns.
panel.setLayout(new GridBagLayout());
panel.setLayout(new CardLayout());
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public CardLayoutDemo() {
JFrame f = new JFrame("CardLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
m2.add(item3);
m2.add(item4);
mb.add(m1);
mb.add(m2);
f.setJMenuBar(mb);
item1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Hello");
}
});
f.setSize(300, 330);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(3);
f.setVisible(true);
}
public static void main(String[] args) {
new MenuDemo();
}
}
Two Event Handling Mechanisms
● The way in which events are handled changed significantly between the original version
of Java (1.0) and all subsequent versions of Java, beginning with version 1.1.
● Although the 1.0 method of event handling is still supported, it is not recommended for
new programs.
● Also, many of the methods that support the old 1.0 event model have been deprecated.
● The modern approach is the way that events should be handled by all new programs
The Delegation Event Model
● The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.
● Its concept is quite simple: a source generates an event and sends it to one or more
listeners.
● In this scheme, the listener simply waits until it receives an event. Once an event is
received, the listener processes the event and then returns.
● The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events.
● In the delegation event model, listeners must register with a source in order to receive
an event notification.
● This provides an important benefit: notifications are sent only to listeners that want to
receive them.
Events
● An event is an object that describes a state change in a source.
● An event can be generated as a consequence of a person interacting with
the elements in a graphical user interface.
● Some of the activities that cause events to be generated are pressing a
button, entering a character via the keyboard, selecting an item in a list, and
clicking the mouse.
● Events may also occur that are not directly caused by interactions with a
user interface.
● For example, an event may be generated when a timer expires, a counter
exceeds a value, software or hardware failure occurs, or an operation is
completed.
Event Sources
● A source is an object that generates an event. This occurs when the internal state of that object
changes in some way.
● Sources may generate more than one type of event.
● A source must register listeners in order for the listeners to receive notifications about a specific
type of event.
● Each type of event has its own registration method.
● Here is the general form:
● public void addTypeListener (TypeListener el )
● For example, the method that registers a keyboard event listener is called addKeyListener( ).
The method that registers a mouse motion listener is called addMouseMotionListener( ).
● When an event occurs, all registered listeners are notified and receive a copy of the
event object.
● A source must also provide a method that allows a listener to unregister an interest in a
specific type of event. The general form of such a method is this:
● public void removeTypeListener(TypeListener el )
● Here, Type is the name of the event, and el is a reference to the event listener.
● For example, to remove a keyboard listener, you would call removeKeyListener( ).
Event Listeners
•A listener is an object that is notified when an event occurs. It has two major requirements.
•First, it must have been registered with one or more sources to receive notifications about specific
types of events.
•Second, it must implement methods to receive and process these notifications.
•The methods that receive and process events are defined in a set of interfaces, such as those
found in java.awt.event.
•For example, the MouseMotionListener interface defines two methods to receive notifications when
the mouse is dragged or moved.
•Any object may receive and process one or both of these events if it provides an implementation of
this interface.
Event Classes
● The classes that represent events are at the core of Java’s event handling
mechanism.
● Thus, a discussion of event handling must begin with the event classes.
● The most widely used events at the time of this writing are those defined by
the AWT and those defined by Swing.
The KeyEvent Class
● A KeyEvent is generated when keyboard input occurs.
● There are three types of key events, which are identified by these integer constants:
○ KEY_PRESSED, KEY_RELEASED, and KEY_TYPED.
● The first two events are generated when any key is pressed or released.
● The last event occurs only when a character is generated.
● Remember, not all keypresses result in characters. For example, pressing shift does not
generate a character.
● There are many other integer constants that are defined by KeyEvent.
● For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the
numbers and letters.
● The KeyEvent class defines several methods, but probably the most commonly used
ones are getKeyChar( ), which returns the character that was entered, and getKeyCode(
), which returns the key code. Their general forms are shown here:
○ char getKeyChar( )
○ int getKeyCode( )
● If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a
KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.
Example
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public Keyboard() {
Frame f = new Frame("Key Event");
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent ke) {
if (ke.getKeyCode()==KeyEvent.VK_ENTER) {
l1.setText(t1.getText());
}
}
});
f.add(t1);
f.add(l1);
f.setSize(300, 300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
The MouseEvent Class
•There are eight types of mouse events. The MouseEvent class defines the following integer
constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.
● Two commonly used methods in this class are getX( ) and getY( ).
● These return the X and Y coordinates of the mouse within the component when the
event occurred.
● Their forms are shown here:
● int getX( )
● int getY( )
● Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse.
It is shown here:
● Point getPoint( )
● It returns a Point object that contains the X,Y coordinates in its integer members: x and y.
● The translatePoint( ) method changes the location of the event. Its form is shown here:
● void translatePoint(int x, int y)
● Here, the arguments x and y are added to the coordinates of the event.
● The getClickCount( ) method obtains the number of mouse clicks for this event. Its
signature is shown here:
● int getClickCount( )
● The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this
platform. Its form is shown here:
● –boolean isPopupTrigger( )
● Also available is the getButton( ) method, shown here:
● int getButton( )
● It returns a value that represents the button that caused the event. For most cases, the
return value will be one of these constants defined by MouseEvent:
● NOBUTTON BUTTON1 BUTTON2 BUTTON3
Event Listener Interfaces
● As explained, the delegation event model has two parts: sources and listeners.
● Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package.
● When an event occurs, the event source invokes the appropriate method defined by the
listener and provides an event object as its argument.
● Table below lists several commonly used listener interfaces and provides a brief
description of the methods that they define.
● The following sections examine the specific methods that are contained in each
interface.
The ActionListener Interface
● The listener interface for receiving action events.
● The class that is interested in processing an action event implements this interface, and
the object created with that class is registered with a component, using the component's
addActionListener method.
● When the action event occurs, that object's actionPerformed method is invoked.
● This interface defines the actionPerformed( ) method that is invoked when an action
event occurs. Its general form is shown here:
● void actionPerformed(ActionEvent ae)
The KeyListener Interface
● The listener interface for receiving keyboard events (keystrokes).
● The class that is interested in processing a keyboard event either implements this
interface (and all the methods it contains) or extends the abstract KeyAdapter class
(overriding only the methods of interest).
● This interface defines three methods. The keyPressed( ) and keyReleased( ) methods
are invoked when a key is pressed and released, respectively. The keyTyped( ) method
is invoked when a character has been entered.
● For example, if a user presses and releases the a key, three events are generated in
sequence: key pressed, typed, and released.
•If a user presses and releases the home key, two key events are
generated in sequence: key pressed and released. The general
forms of these methods are shown here:
–void keyPressed(KeyEvent ke)
–void keyReleased(KeyEvent ke)
–void keyTyped(KeyEvent ke)
•
The MouseListener Interface
● The listener interface for receiving "interesting" mouse events (press, release, click, enter,
and exit) on a component. (To track mouse moves and mouse drags, use the
MouseMotionListener.)
● The class that is interested in processing a mouse event either implements this interface
(and all the methods it contains) or extends the abstract MouseAdapter class (overriding
only the methods of interest).
● This interface defines five methods.
● If the mouse is pressed and released at the same point, mouseClicked( ) is invoked.
● When the mouse enters a component, the mouseEntered( ) method is called.
● When it leaves, mouseExited( ) is called.
● The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is
pressed and released, respectively. The general forms of these methods are shown
here:
● void mouseClicked(MouseEvent me)
● void mouseEntered(MouseEvent me)
● void mouseExited(MouseEvent me)
● void mousePressed(MouseEvent me)
● void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
● The Java MouseMotionListener is notified whenever you move or drag mouse. It is
notified against MouseEvent.
● The MouseMotionListener interface is found in java.awt.event package. It has two
methods.
● void mouseDragged(MouseEvent e);
● void mouseMoved(MouseEvent e);
The MouseWheelListener
● The listener interface for receiving mouse wheel events on a component.
● The class that is interested in processing a mouse wheel event implements this interface
● It has only one method
● void mouseWheelMoved(MouseWheelEvent e)
The WindowListener Interface
● The listener interface for receiving window events.
● The class that is interested in processing a window event either implements this
interface (and all the methods it contains) or extends the abstract WindowAdapter class
(overriding only the methods of interest).
● This interface defines seven methods. The windowActivated( ) and
windowDeactivated( ) methods are invoked when a window is activated or deactivated,
respectively.
● If a window is iconified, the windowIconified( ) method is called.
● When a window is deiconified, the windowDeiconified( ) method is called. When a
window is opened or closed, the windowOpened( ) or windowClosed( ) methods are
called, respectively. The windowClosing( ) method is called when a window is being
closed.
•The general forms of these methods are
–void windowActivated(WindowEvent we)
–void windowClosed(WindowEvent we)
–void windowClosing(WindowEvent we)
–void windowDeactivated(WindowEvent we)
–void windowDeiconified(WindowEvent we)
–void windowIconified(WindowEvent we)
–void windowOpened(WindowEvent we)
The ItemListener Interface
● The listener interface for receiving item events. The class that is interested in processing
an item event implements this interface.
● void itemStateChanged(ItemEvent e)Invoked when an item has been selected or
deselected by the user.
● Model: ButtonModel (holds the state of the button, like whether it is pressed,
enabled, etc.).
● View: The actual button that is drawn on the screen.
● Controller: ActionListener (handles the action events when the button is
pressed).
Example: MVC in a Swing Application
1. The Model
public class CounterModel {
private int count;
public int getCount() {
return count;
}
public void incrementCount() {
count++;
}
}
2. The View
import javax.swing.*;
import java.awt.*;
public class CounterView extends JFrame {
private JButton incrementButton;
private JLabel countLabel;
public CounterView() {
incrementButton = new JButton("Increment");
countLabel = new JLabel("Count: 0");
this.setLayout(new FlowLayout());
this.add(countLabel);
this.add(incrementButton);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(200, 100);
}
public void setCount(int count) {
countLabel.setText("Count: " + count);
}
view.setVisible(true);
}
Explanation
1. Model (CounterModel):
○ Manages the state of the counter.
○ Provides methods to get the current count and increment the count.
2. View (CounterView):
○ Manages the UI components (JButton and JLabel).
○ Provides methods to update the count label and access the increment button.
3. Controller (CounterController):
○ Connects the Model and the View.
○ Updates the Model when the button is clicked and refreshes the View to reflect the new
state.
4. Main (MVCDemo):
○ Creates instances of the Model, View, and Controller.
○ Makes the View visible.