Programming in Java: UNIT-3 (GUI Designing and Event Handling)
Programming in Java: UNIT-3 (GUI Designing and Event Handling)
Programming in Java: UNIT-3 (GUI Designing and Event Handling)
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.
Although Swing eliminates a number of the limitations inherent in the AWT, Swing does not
replace it.
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.
Means that they are written entirely in Java and do not map directly to platform-specific peers.
AWT vs Swing
JFC is short for Java Foundation Classes, which encompass a group of features for
building graphical user interfaces (GUIs) and adding rich graphics functionality and
interactivity to Java applications.
javax.accessibility
javax.swing.plaf
javax.swing.text
javax.swing
javax.swing.plaf.basic
javax.swing.text.html
javax.swing.border
javax.swing.plaf.metal
javax.swing.text.html.parser
javax.swing.colorchooser
javax.swing.plaf.multi
javax.swing.text.rtf
javax.swing.event
javax.swing.plaf.synth
javax.swing.tree
javax.swing.filechooser
javax.swing.table
javax.swing.undo
Container classes
Helper classes
Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet.
When using these classes, you should keep these facts in mind:
Each GUI component can be contained only once. If a component is already in a container and
you try to add it to another container, the component will be removed from the first container
and then added to the second.
Each top-level container has a content pane that, generally speaking, contains (directly or
indirectly) the visible components in that top-level container's GUI.
You can optionally add a menu bar to a top-level container. The menu bar is by convention
positioned within the top-level container, but outside the content pane.
Containment hierarchy
A Swing-based applet has at least one containment hierarchy, exactly one of which
is rooted by a JApplet object. For example, an applet that brings up a dialog has
two containment hierarchies. The components in the browser window are in a
containment hierarchy rooted by a JApplet object. The dialog has a containment
hierarchy rooted by a JDialog object.
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
OR
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.swing that is
implemented by JFrame.
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE
JFrame.EXIT_ON_CLOSE
Jframe.DISPOSE_ON_CLOSE
DO_NOTHING_ON_CLOSE
Do not do anything when the user requests that the window close. Instead, the program
should probably use a window listener that performs some other action in its windowClosing
method.
Hide the window when the user closes it. This removes the window from the screen but
leaves it displayable.
Hide and dispose of the window when the user closes it. This removes the window from the
screen and frees up any resources used by it.
Exit the application, using System.exit(0). This is recommended for applications only. If
used within an applet, a SecurityException may be thrown.
Swing Containers
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.
JPanel
Constructors:
JPanel()
Creates a new JPanel with default flow layout.
JPanel(LayoutManager layout)
Create a new JPanel with the specified layout manager.
Swing Components
Components
Image Icons
The image file names for these types end with .gif, .jpg, and .png, respectively.
Demo Program(ImageDemo.java)
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()
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.
JLabel
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)
Demo Program(MyLabel.java)
JTextField
The integer argument passed to the JTextField constructor, indicates the number of columns in the field
(Minimum number of characters displayed in the TextField).
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.
Demo Program(MyTextfield.java)
JTextArea
Demo Program(MyTextArea.java)
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.
JPasswordField
Demo Program(MyPasswordField.java)
Swing Buttons
Swing defines four types of buttons, all are subclasses of the AbstractButton class,
which extends JComponent.
JButton,
JToggleButton,
JCheckBox, and
JRadioButton
JButton
JButton allows an icon, a string, or both to be associated with the push button.
JButton()
JButton(Icon i)
JButton(String str)
JButton(String str, Icon i)
We can obtain the action command by calling getActionCommand( ) on the event object.
Demo Program(MyButton.java)
JCheckBox
Its immediate super class is JToggleButton, which provides support for twostate buttons.
JCheckBox(String str)
JCheckBox
JCheckBox()
Creates an initially unselected check box button with no text, no icon.
JCheckBox(String text)
Creates an initially unselected check box with text
JCheckBox
Syntax for setting short cut with alt key from keyboard
jcb1.setSelected(true);
jcb1.setActionCommand();
jcb2.getActionCommand();
Demo Program(MyCheckBox.java)
Demo Program(MyCheckBoxWithItemEvent.java)
JRadioButton
Radio buttons are a group of mutually exclusive buttons, in which only one button can be
selected at any one time.
JRadioButton generates action events and item events each time the button selection changes.
JRadioButton
JRadioButton()
Creates an initially unselected radio button with no set text.
JRadioButton(String text)
Creates an unselected radio button with the specified text.
Demo Program(MyRadioButton.java)
JList
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.
JList
Demo Program(MyList.java)
JComboBox
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()
JComboBox(Object[ ]items)
Items can be dynamically added to the list of choices via the addItem( )
method.
void addItem(Object obj)
JComboBox
if (jcb1.getSelectedIndex() != -1)
{
jcb1.getItemAt(jcb1.getSelectedIndex());
jcb.setSelectedIndex(0);
JComboBox
jcb.setForeground(Color.BLUE);
Demo Program(MyComboBox.java)
JMenu
A menu provides a space-saving way to let the user choose one of several options.
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.
Creating JMenu
Create a MenuBar
Create Menus
Create MenuItems
menuBar.add(menu);
setJMenuBar(menuBar);
Creating a submenu
submenu.add(jsm1);
submenu.add(jsm2);
menuA.add(submenu);
Demo Program(MyComboBox.java)
JScrollPane
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 the viewport. It is a window in which the component
being scrolled is displayed.
JScrollPane(Component comp)
JScrollPane
JScrollPane(int, int)
You can also set the policies dynamically with the setHorizontalScrollBarPolicy and
setVerticalScrollBarPolicy methods.
VERTICAL_SCROLLBAR_AS_NEEDED
HORIZONTAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_ALWAYS
HORIZONTAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_NEVER
HORIZONTAL_SCROLLBAR_NEVER
Demo Program(MyMenuBar.java)
JScrollPane
Any number of these empty spaces can be replaced by using the setCorner
method to add a component to a particular corner.
The size of each corner component is entirely determined by the size of the
headers and/or scroll bars that surround it.
scrollPane.getViewport().setBackground().
ScrollPaneLayout determines the size to make the viewport view in one of two
ways:
Layout Managers
FlowLayout
GridLayout
BorderLayout
CardLayout
FLowLayout
You can use the setAlignment, setHgap, and setVgap methods to specify the alignment
and the horizontal and vertical gaps.
flowLayout.setVgap(20);
FLowLayout
Demo Program(MyFlowLayout.java)
GridLayout
GridLayout
Demo Program(MyGridLayout.java)
BorderLayout
BorderLayout
Demo Program(MyBorderLayout.java)
CardLayout
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)
Demo Program(MyCardLayout.java)
Color class
We can set colors for GUI components by using the java.awt.Color class.
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.
Color class
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));
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.
You can choose a font name from SansSerif, Serif, Monospaced, Dialog, or DialogInput.
Font class
Example:
Font font1 = new Font("SansSerif", Font.BOLD, 16);
MVC Architecture
The component for presenting the data, known as a view, handles all
essential component behaviours.
MVC Architecture
It makes multiple views possible so that data can be shared through the
same model. For example, a model storing student names can be
displayed simultaneously in a combo box and a list box.
MVC Architecture
Most events to which our program will respond are generated when the user
interacts with a GUI-based program.
They are passed to our program in a variety of ways, with the specific method
dependent upon the actual event. There are several types of events,
including those generated by the mouse, the keyboard, and various GUI
controls, such as a push button, scroll bar, or check box.
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.
Listener Interface
ActionListener
ItemEvent
ItemListener
itemStateChanged(ItemEvent)
MouseEvent
MouseListener
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseExited(MouseEvent)
mouseEntered(MouseEvent)
MouseMotionListener
KeyEvent
KeyListener
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
Demo Program(MyMouseListener.java)
Demo Program(MyMouseMotionListener.java)
Demo Program(MyKeyListener.java)