0% found this document useful (0 votes)
44 views

Lecture2 GUI Basics

The document discusses graphical user interfaces in Java using Swing. It introduces several common Swing components: - JLabel - Used for displaying read-only text. - JTextField and JPasswordField - Used for single-line text input. JPasswordField masks input. - JButton - Used for clickable buttons that trigger actions. - JComboBox - Presents a dropdown list of selectable items. - JOptionPane - Used for creating modal dialog boxes. The document explains how to create these components, set their properties, register event handlers, and use them to build a basic GUI application with Java Swing.

Uploaded by

Gemechis Tadele
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Lecture2 GUI Basics

The document discusses graphical user interfaces in Java using Swing. It introduces several common Swing components: - JLabel - Used for displaying read-only text. - JTextField and JPasswordField - Used for single-line text input. JPasswordField masks input. - JButton - Used for clickable buttons that trigger actions. - JComboBox - Presents a dropdown list of selectable items. - JOptionPane - Used for creating modal dialog boxes. The document explains how to create these components, set their properties, register event handlers, and use them to build a basic GUI application with Java Swing.

Uploaded by

Gemechis Tadele
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Lecture 2: Graphical User

Interfaces
Objectives - by the end of this chapter, you
should be able to do the following:

– String manipulation
– write a simple graphical user interface in Java
using Swing;
– find out how to use components by browsing the
Swing Tutorial and the Java API;
– program listeners to respond to user generated
events;
– use layout managers to arrange components
attractively in windows
Strings

• string: An object storing a sequence of text


characters.
– Unlike most other objects, a String is not created with
new.
String name = "text";
String name = expression;
– Examples:
String name = "Marla Singer";
int x = 3;
int y = 5;
String point = "(" + x + ", " + y + ")";
Indexes

• Characters of a string are numbered with 0-based


indexes:
String name = "P. Diddy";

index 0 1 2 3 4 5 6 7
char P . D i d d y

– The first character's index is always 0


– The last character's index is 1 less than the string's
length
Methods — Find (indexOf)
0 2 6 10 15

String name =“President George Washington";


Returns:
name.indexOf (‘P'); 0
name.indexOf (‘e'); 2
name.indexOf (“George"); 10
name.indexOf (‘e', 3); 6 (starts searching
at position 3)
name.indexOf (“Bob"); -1 (not found)
name.lastIndexOf (‘e'); 15
Methods — Equality

boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2

b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true

boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2,
case-blind

if(team.equalsIgnoreCase(“raiders”))
System.out.println(“Go You “ + team);
Methods — replace

String word2 = word1.replace(oldCh, newCh);


returns a new string formed from word1 by
replacing all occurrences of oldCh with newCh

String word1 = “rare“;


String word2 = “rare“.replace(‘r’, ‘d’);
//word2 is “dade”, but word1 is still “rare“
Numbers to Strings
Three ways to convert a number into a string:
1. String s = "" + num; Integer and Double
s = “” + 123;//”123” are “wrapper” classes
2. String s = Integer.toString (i); from java.lang that
represent numbers as
String s = Double.toString (d); objects. They also
s = Integer.toString(123);//”123” provide useful static
s = Double.toString(3.14); //”3.14” methods.

3. String s = String.valueOf (num);


s = String.valueOf(123);//”123”
Methods — substring

Returns a new String by copying characters from an existing String.

• String subs = word.substring (i, k); television


– returns the substring of chars in
positions from i to k-1 i k
• String subs = word.substring (i); television
– returns the substring from the i-th
char to the end i
Returns:
”television".substring (2,5); “lev"
“immutable".substring (2); “mutable"
“bob".substring (9); "" (empty string)
Methods — Concatenation

String word1 = “re”, word2 = “think”; word3 = “ing”;


int num = 2;
• String result = word1 + word2;
//concatenates word1 and word2 “rethink“
• String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
• result += word3;
//concatenates word3 to result “rethinking”
• result += num; //converts num to String
//and concatenates it to result “rethinking2”
String Manipulation
Applications
• Given a 100 pages of documents:
– Count the number of words.
– Count the number of Verbs, and Adjectives.
– Count the number of capital letters
– Count Unique words
– Count words written in capital letters
– Count the number of punctuation marks.
– Correct all sentence that begins with small letters
– Replace all capital letters by small letters
• Given the full name of a person, write a program that split it to first
name, middle name and last name.
– Example: Abebe Kebede Lema

– Output: First name: Abebe, Middle name: Kebede, Lat Name: Lema
Review Questions:

1. The String class is part of what package?


2. What does the String class have that other
classes do not have?
3. “Text enclosed in quotes is called ?”
4. What is the returned value for
“ETHIOPIA”.length()?
5. Define immutable objects.
Review (cont’d):

6. How does immutability of Strings make


Java more efficient?
7. How does immutability of Strings make
Java less efficient?
8. How do you declare an empty string?
9. Why are String constructors not used very
often?
10. “CHALA”. equalsIgnoreCase(“chala”)
returns ?
Review (cont’d):

11. String city = “ADDIS ABABA“;


What is returned by city.charAt (2)?
12. By city.substring(2, 4)?
13. By city.lastIndexOf(‘A’)?
14. By city.indexOf(3)?
15. What does the trim method do?
Review (cont’d):

6. “CHALA”. equals (“chala”) returns ?


16. What kind of value does “man”.compareTo(“Man”) return?
17. What will be stored in s?
s = “mint”.replace(‘t’, ‘e’);
18. What does s.toUpperCase() do to s?
19. Name a simple way to convert a number into a string.
20. When to use set instead of ArrayList?
21. Write at least three applications of Map in programming?
22. What is the difference between inheritance and
polymorphism, give an example?
23. Why Java is secure?
24. When to use try catch block and why?
25. What is API?
Introduction

• Up till now you have written programs that


communicate with the end user through a
text-based interface
– Using System.out for output
– Using Keyboard for input.

• Java provides two sets of facilities for


developing GUIs:
– The Abstract Window Toolkit (AWT): package
java.awt
– Swing: package javax.swing
29.1Introduction

• Graphical User Interface ("Goo-ee")


– Pictoral interface to a program
• Distinctive "look" and "feel"

– Different applications with consistent GUIs


improve productivity
• Example: Netscape Communicator
– Menu bar, text field, label
• GUIs built from components
– Component: object with which user interacts
– Examples: Labels, Text fields, Buttons,
Checkboxes
What is Java Swing?

• Part of the Java Foundation Classes (JFC)


• Provides a rich set of GUI components
• Used to create a Java program with a
graphical user interface (GUI)
• table controls, list controls, tree controls,
buttons, and labels, and so on…
What features are available?

• GUI components like button, checkbox, and so on…


• Java 2D API: images, figures, animation
• Pluggable look and feel: use samples or create your
own
• Data Transfer: cut, copy, paste, drag & drop
• Internationalization: supports different input
language, right to left reading
• Accessibility API: for people with disabilities
• Undo Framework API: supports unlimited numbers of
actions to undo and redo
• Flexible Deployment: run within a browser as an
applet or Java Web Start
JLabel

• Labels
– Provide text instructions on a GUI
– Read-only text
– Programs rarely change a label's contents
– Class JLabel (subclass of JComponent)
• Methods
– Can declare label text in constructor
– myLabel.setToolTipText( "Text" )
• Displays "Text"in a tool tip when mouse over label
– myLabel.setText( "Text" )
– myLabel.getText()
JTextField and JPasswordField

• JTextFields and JPasswordFields


– Single line areas in which text can be entered or
displayed
– JPasswordFields show inputted text as *
– JTextField extends JTextComponent
• JPasswordField extends JTextField

• When Enter pressed


– ActionEvent occurs
– Currently active field "has the focus"
• Methods
– Constructor
• JTextField( 10 ) - sets textfield with 10 columns of text
• JTextField( "Hi" ) - sets text, width determined automatically
JTextField and JPasswordField
• Methods (continued)
– setEditable( boolean )
• If true, user can edit text
– getPassword
• Class JPasswordField
• Returns password as an array of type char

• Example
– Create JTextFields and a JPasswordField
– Create and register an event handler
• Displays a dialog box when Enter pressed
JButton
• Button
– Component user clicks to trigger an action
– Several types of buttons
• Command buttons, toggle buttons, check boxes, radio buttons

• Command button
– Generates ActionEvent when clicked
– Created with class JButton
• Inherits from class AbstractButton

• Jbutton
– Text on face called button label
– Each button should have a different label
– Support display of Icons
Example Summary

• ButtonGroup ensures that only one radio


button in the group can be selected at a time.
• setSelected sets initial state. (Good for
defaults).
• isSelected checks the state of the button.
JComboBox

• A combo box is a button that when pressed,


presents a list of items that can be selected.
Dialogs - JOptionPane
• Dialogs are windows that are more limited than frames.
• Every dialog is dependent on a frame. When that frame is
destroyed, so are its dependent dialogs. When the frame is
iconified, its dependent dialogs disappear from the screen. When
the frame is deiconified, its dependent dialogs return to the screen.
• To create simple dialogs, use the JOptionPane class.
• The dialogs that JOptionPane provides are modal.
• When a modal dialog is visible, it blocks user input to all other
windows in the program.
JOptionPane Examples
// show Yes/No dialog
int x = JOptionPane.showConfirmDialog(null,
"choose one", "choose one", JOptionPane.YES_NO_OPTION);
System.out.println("User clicked button " + x);
JOptionPane Examples
// show input dialog
String inputValue = JOptionPane.showInputDialog("Please
input “ +
“a value");
System.out.println("User entered " + inputValue);
Swing Components
Swing Components
Using Swing Components

• Very simple, just create object from


appropriate class – examples:
– JButton but = new JButton();
– JTextField text = new JTextField();
– JTextArea text = new JTextArea();
– JLabel lab = new JLabel();
• Many more classes. Don’t need to know
every one to get started.
• See ch. 9 Hortsmann
Main Steps in GUI
Programming
To make any graphic program work we must be able to
create windows and add content to them.

To make this happen we must:

1. Import the awt or swing packages.


2. Set up a top-level container.
3. Fill the container with GUI components.
4. Install listeners for GUI Components.
5. Display the container.
Containment Hierarchy of the
Hello World Example

JFrame


content pane

JLabel
A first Swing application

import javax.swing.*; When you run


public class FirstGUI this program, a
tiny window
{ appears:
public static void main(String[] args)
{
JFrame f = new JFrame(); The close
f.setVisible(true); button does not
work (have to
} Class for
press “Stop” in
} drawing a
Ready)
Displays the window
window and on the
enters the screen
event loop.
Shutting down the
application properly
Need to add a
import javax.swing.*; single
public class FirstGUI { statement to
public static void main(String[] args) { program the
JFrame f = new JFrame( ); close button
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}

• To give the application a title, give the constructor a


string: JFrame f = new JFrame( “My first GUI”);
Components and containers

• A component is any GUI element, such as a window,


button or label.
• A container is a type of component that has the
purpose of containing other components.
• Types of containers:
– Top-level containers: Every Swing program contains at least
one top-level container (e.g. JFrame, JDialog or JApplet).
Top-level containers cannot be added to other containers.
– Intermediate containers: used to group components so that
they can be handled as a single component (e.g JPanel,
JTabbedPane).
– Atomic components (basic controls): cannot contain other
components (e.g JButton, JTextField).
Adding a button to the
application
import javax.swing.*;
public class FirstGUI
{
public static void main(String[] args)
{
JFrame f = new JFrame( );
JButton button = new JButton("Press me!"); // create a button
f.getContentPane().add(button); // add the button to the frame
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack( );
f.setVisible(true);
}
}
Organising the code in a
better way
• As we start adding more components, the main
method will become too large and messy.
• A better way:
– Create a class that extends JFrame
– Put all components into the class (as data members)
– Do the rest in the constructor
import javax.swing.*;
public class SimpleFrame extends JFrame {
private JButton button = new JButton("Press me!");
public SimpleFrame( ) {
getContentPane( ).add(button);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
}
Input
• So we now know how to present widgets on the screen

• A program also needs to react to the user's actions

• Examples:
– When the user presses a button we want to save a file
– When the user closes the program we want to ask “are you
sure?”
– ...

• Swing mechanism: Events and Listeners


Events, Listeners
• Swing defines all sorts of Listener interfaces
– E.g.: ActionListener, MouseMotionListener,
WindowListener, ...

public interface ActionListener extends EventListener {


public void actionPerformed(ActionEvent e);
}

public interface MouseMotionListener extends EventListener {


public void mouseDragged(MouseEvent e);
public void mouseMoved(MouseEvent e);
}

• There are default (empty) implementations for many of the listeners


– E.g.: MouseMotionAdapter, WindowAdapter
Event Handling Demo: GUI
What are events?

• All components can listen for one or more


events.
• Typical examples are:
– Mouse movements
– Mouse clicks
– Hitting any key
– Hitting return key
– etc.
• Telling the GUI what to do when a particular
event occurs is the role of the event handler.
ActionEvent

• In Java, most components have a special


event called an ActionEvent.
• This is loosely speaking the most common or
canonical event for that component.
• A good example is a click for a button.
• To have any component listen for
ActionEvents, you must register the
component with an ActionListener. e.g.
– button.addActionListener(new MyAL());
actionPerformed

• The actionPerformed method has the


following signature:
void actionPerformed(ActionEvent)
• The object of type ActionEvent passed to the
event handler is used to query information
about the event.
• Some common methods are:
– getSource()
• object reference to component generating event
– getActionCommand()
• some text associated with event (text on button, etc).
Getting the button to do
something
• Currently, if the user clicks on our button, nothing
happens.
• We would like to change the program, so that the
label changes when the button is clicked:

• The code that responds to that event of the user


clicking the mouse on our button is called the listener
for that button.
• We would therefore like to program the listener of the
button to have the code:
label.setText(" Ouch ... that hurt! ");
Event Handling
• Every time the user types a character or pushes a mouse
button, an event occurs. Any object can be notified of the event.
All it has to do is implement the appropriate interface and be
registered as an event listener on the appropriate event source.
:
• Act that results in the event Listener type:
• User clicks a button, presses Return while typing in a text field,
or chooses a menu item ActionListener
• User closes a frame (main window) WindowListener
• User presses a mouse button while the cursor is over a
component MouseListener
• User moves the mouse over a component
MouseMotionListener
• Component becomes visible ComponentListener
• Component gets the keyboard focus FocusListener
• Table or list selection changes ListSelectionListener
New Button Event examples

• First example

• Improved example
TextField Event example
Panels

• Container that can hold other components


• “miniature frame” – no title bar or border
• Panels can contain other panels
• Each panel can have its own layout
Top Level Component

JFrame getContentPane()
JFrame
Panels

• Container that can hold other components


• “miniature frame” – no title bar or border
• Panels can contain other panels
• Each panel can have its own layout

JPanel One main panel


(background)
getContentPane.add()
Panels

• Container that can hold other components


• “miniature frame” – no title bar or border
• Panels can contain other panels
• Each panel can have its own layout

More panels for organisation


JPanel

JPanel
background.add()
Panels

• Container that can hold other components


• “miniature frame” – no title bar or border
• Panels can contain other panels
• Each panel can have its own layout

B
JTextArea
Atomic components
B
B
JTextArea
B
Arranging components

• Layout managers are used to control the size


and position of components in containers.
• The Java platform provides a number of
layout managers, including BorderLayout,
FlowLayout and GridLayout.
• To use layout mangers, you have to import
java.awt.*.
• To use a particular layout manager, you use
the setLayout method.

You might also like