Anda di halaman 1dari 34

CHAPTER SEVEN

JAVA
GRAPHICAL USER INTERFACE
GUI
Introduction to GUI
A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application.
A GUI (pronounced "goo-ee") gives an application a distinctive
"look" and "feel."
It provides different applications with consistent, intuitive user
interface components allows users to be somewhat familiar with an
application, so that they can learn it more quickly and use it
more productively.
Overview Of Swing Components
Most Swing components are pure Java components they are
written, manipulated and displayed completely in Java.
They are part of the Java Foundation Classes (JFC)Java's
libraries for cross-platform GUI development. There are actually two
sets of GUI components in Java. Before Swing was introduced in J2SE
1.2, Java GUIs were built with components from the Abstract
Window Toolkit (AWT) in package java.awt.
Overview Of Swing Components
When a Java application with an AWT GUI executes on
different Java platforms, the application's GUI components display
differently on each platform. i.e. GUI app in Windows differs from
Mac.
Together, the appearance and the way in which the user interacts with
the application are known as that application's look-and-feel.
Swing GUI components allow you to specify a uniform look-
and-feel for your application across all platforms or to use
each platform's custom look-and-feel.
Overview Of Swing Components
An application can even change the look-and-feel during execution
to enable users to choose their own preferred look-and-feel.
Most Swing components are not tied to actual GUI components
supported by the underlying platform on which an application
executes.
Such GUI components are known as lightweight components. For
this reason, Swing GUI components are generally preferred.
Overview Of Swing Components
In Swing, classes that represent GUI components have names
beginning with the letter J.
Some examples are JButton, JLabel, JFrame, JTextField, JCheckBox,
JComboBox, JRadioButton, JMenu, Jslider and so on.
Altogether there are more than 250 new classes and 75 interfaces in
Swing, the figure shown below depicts the Java Swing class hierarchy.
Overview Of Swing Components
Overview Of Swing Components
Overview Of Swing Components
Overview Of Swing Components
1. JPanel is swing's version of the AWT class panel and uses the same
default layout, Flowlayout and it is descended directly from JComponent.
2. JFrame is swing's version of frame and is descended directly from that
class. The components added to the frame are referred to as its contents;
these are managed by the contentPane. To add a component to a
JFrame, we must use its contentPane instead.
3. FlowLayout are used to arrange swing components from left to right
until there's no more space available. Then it begins a new row below it
and moves from left to right again. Each component in a FlowLayout gets
as much space as it needs and no more.
Overview Of Swing Components
4. GridLayout is a layout manager that lays out a container's components in
a rectangular grid in row by column manner as per provided by the user.
The container is divided into equal-sized rectangles, and one component
is placed in each rectangle.
5. JLabel descended from JComponent, is used to create text labels that
can not be edited live but are capable of modified in order.
6. AbstractButton is an abstract class which extends class JComponent and
provides a foundation for a family of button classes, including JButton.
JButton is a component the user clicks to trigger a specific action.
Overview Of Swing Components
7. JTextField allows editing of a single line of text. New features include
the ability to justify the text left, right, or center, and to set the text's
font.
8. JPasswordField (a direct subclass of JTextField ) you can suppress the
display of input. Each character entered can be replaced by echo
character. This allows confidential input for passwords, for example. By
default, the asterisk, *.
9. JTextArea allows editing of multiple lines of text. JTextArea can
be used in conjunction with class JScrollPane to achieve scrolling.
Overview Of Swing Components
The underlying JScrollPane can be forced to always or never have
either the vertical or horizontal scrollbar;
10. JRadioButton is similar to JCheckbox, except for the default
icon for each class. A set of radio buttons can be associated
as a group in which only one button at a time can be selected.
11. JCheckBox is not a member of a checkbox group. A checkbox can
be selected and deselected, AND it also displays its current state.
Overview Of Swing Components
12. JComboBox is like a drop down box. You can click a drop-down
arrow and select an option from a list. For example, when the
component has focus, pressing a key that corresponds to the first
character in some entry’s name selects that entry. A vertical scrollbar is
used for longer lists.
13. JMenubar can contain several JMenu’s. Each of the JMenu’s can
contain a series of JMenuItem ’s that it can let you select one. Swing
provides support for pull-down and popup menus.
Overview Of Swing Components
Java Swing Example:
Below is a java swing code for the traditional Hello World program.
import javax.swing.JFrame;
import javax.swing.JLabel; OUTPUT:
public class HelloWorldFrame extends JFrame {
HelloWorldFrame(){
JLabel jlbHelloWorld = new JLabel("Hello World");
add(jlbHelloWorld);
this.setSize(200, 100);
setVisible(true);
public static void main(String args[]) {
new HelloWorldFrame();
} } }
JFrame
JFrame is a Window with border, title and buttons. When JFrame is set
visible, an event dispatching thread is started.
JFrame objects store several objects including a Container object
known as the content pane. To add a component to a JFrame, add it to
the content pane.
JFrame Constructors
JFrame() : Constructs a new frame that is initially invisible.
JFrame(String title) : Creates a new, initially invisible Frame with the
specified title.
JFrame Contnd…
Steps to create a JFrame windows are as follows:
Step 1: Construct an object of the JFrame class.
Step 2: Set the size of the JFrame.
Step 3: Set the title of the JFrame to appear in the title bar (title bar will be
blank if no title is set).
Step 4: Set the default close operation. When the user clicks the close
button, the program stops running.
Step 5: Make the JFrame visible.
JFlowLayout
It is an AWT component used to arrange
swing components from left to right until panel.add(new JCheckBox("JCheckBox 3"));

there’s no more space available. panel.add(new JTextField("Long-Named JTextField


4"));
import java.awt.FlowLayout.*;
panel.add(new JButton("JButton 5"));
import javax.swing.*;
setVisible(true);
public class FlowLayoutDemo extends JFrame{
setSize(300,350); }
FlowLayoutDemo() {
public static void main(String[] args) {
super("FlowLayout Source Demo");
FlowLayoutDemo flowLayout = new FlowLayoutDemo();
JPanel panel = new JPanel();
flowLayout.setDefaultCloseOperation(JFrame.EXIT_ON_
add(panel);
CLOSE);
panel.setLayout(new FlowLayout());
}
panel.add(new JLabel("JLabel 1"));
}
panel.add(new JButton("JButton 2"));
JFlowLayout Contnd…
OUTPUT:
GridLayout
It is a layout manager that lays out a container’s components in a
rectangular grid. The container is divided into equal-sized rectangles,
and one component is placed in each rectangle.
GridLayout Constructors
GridLayout() : Creates a grid layout with a default of one column per component,
in a single row.
GridLayout(int rows, int cols) : Creates a grid layout with the specified number of
rows and columns.
JFrame Contnd…
Steps to create a JFrame windows with predefined layout are as follows:
Step 1: Construct an object of the JFrame class.
Step 2: Set the size of the JFrame.
Step 3: Set the title of the JFrame to appear in the title bar (title bar will be
blank if no title is set).
Step 4: Set up the content pane and components in a layout FlowLayout,
GridLayout etc.
Step 5: Set the default close operation.
Step 6: Make the JFrame visible.
JLabel
JLabel, descended from JComponent, is used to create text labels.
A JLabel object provides text instructions or information on a GUI;
display a single line of read-only text, an image or both text and image.
We use a Swing JLabel when we need a user interface component
that displays a message or an image.
JLabel Constructor
JLabel() : Creates a JLabel instance with no image and with an empty string for the title.
JLabel(Icon image) :Creates a JLabel instance with the specified image.
JLabel(String text) : Creates a JLabel instance with the specified text.
Introduction to Event Handling
Normally, a user interacts with an application’s GUI to indicate the tasks that the
application should perform.
For example, when you write an e-mail in an e-mail application, clicking the send button
tells the application to send the e-mail to the specified e-mail addresses.
GUIs are event driven. When the user interacts with a GUI component, the interaction
known as an event drives the program to perform a task.
Some common events (user interactions) that might cause an application to perform a task
include clicking a button, typing in a text field, selecting an item from a menu, closing a
window and moving the mouse.
 The code that performs a task in response to an event is called an event handler and the
overall process of responding to events is known as event handling.
More on Event Handling
Both AWT and Swing applications uses the AWT event-handling classes (in package java.awt.event).
Swing added a few new event handling classes (in package javax.swing.event), but they are not
frequently used.
AWT GUI Components (such as Button, TextField, ComboBox, CheckBox and Window) can trigger an
AWTEvent upon user’s activation.
More on Event Handling
ActionEvent & ActionListener
An ActionEvent is fired, when an action has been performed by the user.
For examples, when the user clicks a button, chooses a menu item, presses enter key in a text field.
The associated ActionListener interface declares only one abstract method, as follows:
ActionListner Method Definition:
public interface ActionListener extends java.util.eventlistener {
public void actionPerformed(ActionEvent evt); // called-back when an action
//has been performed
}
More on Event Handling
Example source code:
The example illustrates a source code fragment which clears a text in text field when the clear button pressed.
JPanel panel = new JPanel();
JTextfield1 jTextField1 = new JTextField();

JButton jBtnClear new JButton(“CLEAR”)


panel.setLayout(new GridLayout(1,2));
add(panel, BorderLayout.CENTER);
panel.add(jBtnClear);
panel.add(jTextField1);
jBtnClear.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {


jTextfield1.setText("");
}});
JTextField
It allows editing/displaying of a single line of text.
When the user types data into them and presses the Enter key, an action
event occurs.
If the program registers an event listener, the listener processes the event
and can use the data in the text field at the time of the event in the program.
JTextField is an input area where the user can type in characters.
JTextField Contnd…
If you want to let the user enter multiple lines of text, you cannot use
JTextfield’s unless you create several of them.
The solution is to use JTextArea which enables the user to enter multiple lines
of text.
JTextField Constructor
JTextField() : Constructs a new TextField.
JTextField(String text): Constructs a new TextField initialized with the specified
text.
All search engine applications are of typical examples of JTextFields.
JButton
JButton is a component that the user clicks to trigger a specific action.
A Java application can use several types of buttons, including command
buttons, checkboxes, toggle buttons and radio buttons.
JButton Constructors
JButton() : Creates a button with no set text or icon.
JButton(Action a) : Creates a button where properties are taken from the
Action supplied.
JButton(String text) : Creates a button with text.
JComboBox
JComboBox is like a drop down box that you can click a drop-down arrow and select
an option from a list.
It generates ItemEvent. For example, when the component has focus, pressing
a key that corresponds to the first character in some entry’s name selects that
entry. A vertical scrollbar is used for longer lists.

JComboBox Constructors
JComboBox() : Creates a JComboBox with a default data model.
JComboBox(Object[] items) :Creates a JComboBox that contains the elements in the
specified array.
JComboBox(Vector items) : Creates a JComboBox that contains the elements in the
specified Vector.
JMenus
Swing provides support for pull-down and popup menus.
A JMenubar can contain several JMenus. And each of the JMenus can contain a series
of JMenuItems that you can select.
How Menus are created?
1. First, a JMenubar is created
2. Then, we attach all of the menus to this JMenubar.
3. Then we add JMenuItems to the JMenus.
4. The JMenubar is then added to the frame. By default, each JMenuItem added to a JMenu is
enabled, that is, it can be selected.
JMenus
import java.awt.*; JMenu menu1, menu2, submenu;

import java.awt.event.*; JMenuItem New,subMenuItem;

import javax.swing.JMenu; JMenuDemo() {

import javax.swing.JMenuItem; super("Microsoft Word");

import javax.swing.JMenuBar; mainMenuBar = new JMenuBar();

import javax.swing.JPanel; menu1 = new JMenu("File");

import javax.swing.JTextArea; menu1.setMnemonic(KeyEvent.VK_F);

import javax.swing.JFrame; mainMenuBar.add(menu1);

public class JMenuDemo extends JFrame implements New = new JMenuItem("New");


ActionListener{ New.addActionListener(this);
JTextArea jtAreaOutput; menu1.add(New);
JMenuBar mainMenuBar; menu1.addSeparator();
JMenus
// Sub Menu follows a seperator // return mainMenuBar;

submenu = new JMenu("Send To:"); JPanel jplContentPane = new JPanel();

submenu.setMnemonic(KeyEvent.VK_D); jplContentPane.setLayout(new FlowLayout());


jtAreaOutput = new JTextArea(5, 30);
subMenuItem = new JMenuItem("My Document");
jplContentPane.add(jtAreaOutput);
subMenuItem.addActionListener(this);
add(jplContentPane);
submenu.add(subMenuItem);
setSize(400, 300);
menu1.add(submenu);
setVisible(true);
// Build second menu in the menu bar.
}
menu2 = new JMenu("Edit");
menu2.setMnemonic(KeyEvent.VK_E);
mainMenuBar.add(menu2);
JMenus
public void actionPerformed(ActionEvent e) {
JMenuItem source = (JMenuItem) (e.getSource());
String s = "Menu Item source: " + source.getText();
jtAreaOutput.setText(s);
}
public static void main(String[] args) {
JMenuDemo frame= new JMenuDemo();
frame.setJMenuBar(frame.mainMenuBar);
The End
frame.setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
} }

Anda mungkin juga menyukai