string class string class in package java.lang string is a class not a primitive data type string...

96
String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand notation String str = “This is my string” An empty string is not the same as an uninitialised string String str; // uninitialised = null String str=“”; // empty

Post on 22-Dec-2015

243 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Class

• String Class in package java.lang• String is a class not a primitive data type• String constants can be created using a traditional

shorthand notation– String str = “This is my string”

• An empty string is not the same as an uninitialised string– String str; // uninitialised = null– String str=“”; // empty

Page 2: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Class• Strings unlike other objects have an operator

defined for them: + for string concatenation – str = str1 + str2 + “another string”;

• String concatenation– Using the + operator with two Strings concatenates

them into a new String– Using the + operator with a String and a value of

another data type concatenates the String with a String representation of the other value

• When the other value is an object, its toString method is called to generate its String representation

Page 3: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Class

• Strings unlike other objects have an operator defined for them: + for string concatenation – str = str1 + str2 + “another string”;

• Once created the contents of a String cannot be changed– to alter the contents of strings use another class

StringBuffer

• String class has a comprehensive list of constructors and methods available

Page 4: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Concat and +concat() - Concatenates the specified string to the end of this

string. If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, containing the invoking string with the contents of the str appended to it.

public String concat(String str)

"to".concat("get").concat("her") returns "together"

Page 5: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Note

• The following program uses the following toUpperCase method

Page 6: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations• toLowerCase(): Converts all of the characters in a String to

lower case.• toUpperCase(): Converts all of the characters in this String to

upper case.

public String toLowerCase()

public String toUpperCase()

Eg: “HELLO THERE”.toLowerCase();

“hello there”.toUpperCase();

Page 7: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Uppercase Program

• import javax.swing.JOptionPane; • import java.lang.*;• public class Capstring1 {• public static void main(String args []){• String firststr1,s2;• firststr1 =

JOptionPane.showInputDialog("Enter String");

Page 8: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

• s2 = firststr1.toUpperCase();• JOptionPane.showMessageDialog(null,

"Result is "+ s2,"outcome", JOptionPane.PLAIN_MESSAGE);

}}

Page 9: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Example Input

Page 10: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Example Output

Page 11: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Notes

• In this program we could not change• The string firststr1• In order to effect the change to all Capital

letters we had to use another string variable s2.

Page 12: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Strings

• Java string is a sequence of characters. They are objects of type String.

• Once a String object is created it cannot be changed. Stings are Immutable.

• To get changeable strings use the class called StringBuffer.• String and StringBuffer classes are declared final, so there

cannot be subclasses of these classes.• The default constructor creates an empty string.

String s = new String();

Page 13: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Creating Strings

• String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'};

String str = new String(data);

• If data array in the above example is modified after the string object str is created, then str remains unchanged.

• Construct a string object by passing another string object.

String str2 = new String(str);

Page 14: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Class

• The String class example of some of the methods – General – length(),

• charAt(), getchars()– Comparing Strings –

• compareTo() startsWith(), endsWith()– Locating Characters

• indexOf(), lastIndexOf()– Extracting substrings

• subString()

Page 15: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations

• The length() method returns the length of the string. Eg: System.out.println(“Hello”.length()); // prints 5

• The + operator is used to concatenate two or more strings.Eg: String myname = “Harry”

String str = “My name is” + myname+ “.”;• For string concatenation the Java compiler converts an

operand to a String whenever the other operand of the + is a String object.

Page 16: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Example import javax.swing.JOptionPane; import java.lang.*;public class Lengthstring1 {

public static void main(String args []){String firststr1,s2;firststr1 = JOptionPane.showInputDialog("Enter String");int l = firststr1.length

//StringBuffer sb = new StringBuffer(firstnum1);//sb = sb.reverse();JOptionPane.showMessageDialog(null, "Length is "+ l ,"outcome", JOptionPane.PLAIN_MESSAGE);

}}

Page 17: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Notes

• The variable l is an integer but the expression• “length is” + l is a string and is output as:• For example if input is Manchester United

Page 18: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand
Page 19: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Exercises

• 1: Enter 2 strings and output the longest.• 2: Print Out an error message if a string is

input which is longer than 15 characters.

Page 20: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations

• equals() - Compares the invoking string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as the invoking object. public boolean equals(Object anObject)

• equalsIgnoreCase()- Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case. public boolean equalsIgnoreCase(String anotherString)

Page 21: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Exercise

• Write a program which asks the following question and tests if the users answers is correct or not.

• Question• What is the Capital City of Ireland• Answer • Dublin

Page 22: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations• compareTo() - Compares two strings lexicographically.

– The result is a negative integer if this String object lexicographically precedes the argument string.

– The result is a positive integer if this String object lexicographically follows the argument string.

– The result is zero if the strings are equal.– compareTo returns 0 exactly when the equals(Object) method would

return true.

public int compareTo(String anotherString)

public int compareToIgnoreCase(String str)

Page 23: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Example Programimport javax.swing.JOptionPane; import java.lang.*;public class Compstring1 {

public static void main(String args []){String firststr1,s2;firststr1 = JOptionPane.showInputDialog("Enter String");s2 = JOptionPane.showInputDialog("Enter another String");if (firststr1.compareTo(s2) < 0)JOptionPane.showMessageDialog(null, firststr1 + "precedes "+ s2,"outcome", JOptionPane.PLAIN_MESSAGE);else

JOptionPane.showMessageDialog(null, s2 + "precedes "+ firststr1,"outcome", JOptionPane.PLAIN_MESSAGE);

}}

Page 24: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

For inputs

• Cat• Dog• We get output:

Page 25: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand
Page 26: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations• replace()- Returns a new string resulting from replacing all

occurrences of oldChar in this string with newChar.

public String replace(char oldChar, char newChar)

"mesquite in your cellar".replace('e', 'o') returns "mosquito in your collar"

Page 27: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Example with replace

import javax.swing.JOptionPane; import java.lang.*;public class Replacestring1 {

public static void main(String args []){String firstnum1,s2;firstnum1 = JOptionPane.showInputDialog("Enter String");s2 = firstnum1.replace('a','o');

//StringBuffer sb = new StringBuffer(firstnum1);//sb = sb.reverse();JOptionPane.showMessageDialog(null, "Result is "+ s2,"outcome", JOptionPane.PLAIN_MESSAGE);

}}

Page 28: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

For Input “hat”

• We get output

Page 29: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand
Page 30: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Exercise

• Write a program to• Replace all vowels in a word with *’s

Page 31: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Other string operations

• We will see some of these again when we look at a changeable string class String Buffer

Page 32: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String OperationsindexOf – Searches for the first occurrence of a character or substring.

Returns -1 if the character does not occur.

public int indexOf(int ch)- Returns the index within this string of the first occurrence of the specified character. public int indexOf(String str) - Returns the index within this string of the first occurrence of the specified substring.

String str = “How was your day today?”;str.indexof(‘t’); str(“was”);

Page 33: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operationspublic int indexOf(int ch, int fromIndex)- Returns the

index within this string of the first occurrence of the specified character, starting the search at the specified index.

public int indexOf(String str, int fromIndex) - Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

String str = “How was your day today?”;str.indexof(‘a’, 6); str(“was”, 2);

Page 34: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String OperationslastIndexOf() –Searches for the last occurrence of a character or

substring. The methods are similar to indexOf().substring() - Returns a new string that is a substring of this

string. The substring begins with the character at the specified index and extends to the end of this string.

public String substring(int beginIndex)

Eg: "unhappy".substring(2) returns "happy"

Page 35: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations• public String substring(int beginIndex, int endIndex)

Eg: "smiles".substring(1, 5) returns "mile“

Page 36: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations

• Characters in a string can be extracted in a number of ways.public char charAt(int index)

– Returns the character at the specified index. An index ranges from 0 to length() - 1. The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

char ch;

ch = “abc”.charAt(1); // ch = “b”

Page 37: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations• trim() - Returns a copy of the string, with leading and trailing

whitespace omitted. public String trim()

String s = “ Hi Mom! “.trim();S = “Hi Mom!”

• valueOf() – Returns the string representation of the char

array argument.

public static String valueOf(char[] data)

Page 38: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations• The contents of the character array are copied; subsequent

modification of the character array does not affect the newly created string.

Other forms are:public static String valueOf(char c) public static String valueOf(boolean b)public static String valueOf(int i)public static String valueOf(long l)public static String valueOf(float f)public static String valueOf(double d)

Page 39: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations

• getChars() - Copies characters from this string into the destination character array.public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

– srcBegin - index of the first character in the string to copy. – srcEnd - index after the last character in the string to copy. – dst - the destination array. – dstBegin - the start offset in the destination array.

Page 40: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations• startsWith() – Tests if this string starts with the specified

prefix.public boolean startsWith(String prefix)“Figure”.startsWith(“Fig”); // true

• endsWith() - Tests if this string ends with the specified suffix. public boolean endsWith(String suffix)

“Figure”.endsWith(“re”); // true

Page 41: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations• startsWith() -Tests if this string starts with the specified prefix

beginning at a specified index. public boolean startsWith(String prefix, int toffset)

prefix - the prefix.

toffset - where to begin looking in the string.

“figure”.startsWith(“gure”, 2); // true

Page 42: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer• A StringBuffer is like a String, but can be modified.• The length and content of the StringBuffer sequence can be

changed through certain method calls.• StringBuffer defines three constructors:

– StringBuffer()– StringBuffer(int size)– StringBuffer(String str)

Page 43: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer Class

• A StringBuffer is like a String but it can be modified• The principle operations on a StringBuffer are

append() and insert()

String s = "a" + "b“ + 4 ;System.out.println(s);

StringBuffer sb = new StringBuffer();sb.append("a");sb.append(4);sb.insert(1,"b");System.out.println (sb);

Page 44: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer Operations• The principal operations on a StringBuffer are the append and

insert methods, which are overloaded so as to accept data of any type.

Here are few append methods:StringBuffer append(String str)StringBuffer append(int num)

• The append method always adds these characters at the end of the buffer.

Page 45: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer Operations• The insert method adds the characters at a specified point.

Here are few insert methods: StringBuffer insert(int index, String str)StringBuffer append(int index, char ch)

Index specifies at which point the string will be inserted into the invoking StringBuffer object.

Page 46: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Example program

• Note this uses the charAT method

Page 47: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

String Operations

• Characters in a string can be extracted in a number of ways.public char charAt(int index)

– Returns the character at the specified index. An index ranges from 0 to length() - 1. The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

char ch;

ch = “abc”.charAt(1); // ch = “b”

Page 48: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

This program take a string as input

• And duplicates every character in it

Page 49: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

import javax.swing.JOptionPane; import java.lang.*;public class Changestring1 {

public static void main(String args []){String firststr1;firststr1 = JOptionPane.showInputDialog("Enter String");

StringBuffer sb = new StringBuffer(firststr1);int l = sb.length();

Page 50: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

for (int i = 0; i < 2*l;i++) {char k = sb.charAt(i);sb = sb.insert(i,k);i++;}JOptionPane.showMessageDialog(null, "Result is "+ sb,"outcome", JOptionPane.PLAIN_MESSAGE);

}}

Page 51: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Input

Page 52: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Output is

Page 53: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Notes about the program

• It passes the entered string into the String Buffer constructor in order to get an equivalent

• It retrieves each character using charAt• It uses the insert method to insert in a copy of

that character

Page 54: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer Operations • replace() - Replaces the characters in a substring of this

StringBuffer with characters in the specified String. public StringBuffer replace(int start, int end,

String str)

• substring() - Returns a new String that contains a subsequence of characters currently contained in this StringBuffer. The substring begins at the specified index and extends to the end of the StringBuffer.

public String substring(int start)

Page 55: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer Operations• reverse() - The character sequence contained in this string

buffer is replaced by the reverse of the sequence. public StringBuffer reverse()

• length() - Returns the length of this string buffer. public int length()

Page 56: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer Operations• capacity() - Returns the current capacity of the String buffer.

The capacity is the amount of storage available for newly inserted characters.

public int capacity()

• charAt() - The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.

public char charAt(int index)

Page 57: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer Operations• getChars() - Characters are copied from this string buffer into

the destination character array dst. The first character to be copied is at index srcBegin; the last character to be copied is

at index srcEnd-1. public void getChars(int srcBegin, int srcEnd,

char[] dst, int dstBegin)

• setLength() - Sets the length of the StringBuffer. public void setLength(int newLength)

Page 58: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

StringBuffer Operations• delete() - Removes the characters in a substring of this

StringBuffer. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the StringBuffer if no such character exists. If start is equal to end, no changes are made.

public StringBuffer delete(int start, int end)

Page 59: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Examples: StringBuffer StringBuffer sb = new StringBuffer(“Hello”);

sb.length(); // 5

sb.capacity(); // 21 (16 characters room is added if no size is specified)

sb.charAt(1); // e

sb.setCharAt(1,’i’); // Hillo

sb.setLength(2); // Hi

sb.append(“l”).append(“l”); // Hill

sb.insert(0, “Big “); // Big Hill

Page 60: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Examples: StringBuffer

sb.replace(3, 11, “”); // Big

sb.reverse(); // gib

Page 61: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Example Program

• Purpose accept as input a string of the form• Part1-part2• And to split it into two separate parts e.g.• “a-b”• First element is a• Second element is b

Page 62: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

import javax.swing.JOptionPane; import java.lang.*;public class Parsestring1 {

public static void main(String args []){String firstnum1;firstnum1 = JOptionPane.showInputDialog("Enter Code");

StringBuffer sb = new StringBuffer(firstnum1);int l = sb.length();StringBuffer sb1 = new StringBuffer();StringBuffer sb2 = new StringBuffer();

Page 63: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

int k = sb.indexOf("-");sb1 = sb1.append(sb.substring(0,k));sb2 = sb2.append(sb.substring(k+1,l));JOptionPane.showMessageDialog(null, "First part is "+ sb1,"outcome", JOptionPane.PLAIN_MESSAGE);

JOptionPane.showMessageDialog(null, "Second part is "+ sb2,"outcome", JOptionPane.PLAIN_MESSAGE);

}}

Page 64: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Input

Page 65: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Output1

Page 66: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Output 2

Page 67: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Exercise

• Write a program which accepts as input a string of the form “3+5” and which calculates the result

Page 68: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Exercises

• Show two ways to concatenate the following two strings together to get the string "Hi, mom.": String hi = "Hi, "; String mom = "mom.";

• Write a program that computes your initials from your full name and displays them.

• An anagram is a word or a phrase made by transposing the letters of another word or phrase; for example, "parliament" is an anagram of "partial men," and "software" is an anagram of "swear oft." Write a program that figures out whether one string is an anagram of another string. The program should ignore white space and punctuation.

Page 69: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

• Exercise 1: Show two ways to concatenate the following two strings together to get the string "Hi, mom.":

• String hi = "Hi, ";• String mom = "mom.";• Answer 1: hi.concat(mom) and hi + mom.

Page 70: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

•Exercise 2: Write a program that computes your initials from your full name and displays them. Answer 2: ComputeInitials

• public class ComputeInitials {• public static void main(String[] args) {• String myName = "Fred F. Flintstone";• StringBuffer myInitials = new

StringBuffer();•

Page 71: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

• int length = myName.length();

• for (int i = 0; i < length; i++) {• if

(Character.isUpperCase(myName.charAt(i))) {•

myInitials.append(myName.charAt(i));• }• }• System.out.println("My initials are: " +

myInitials);• }• }

Page 72: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

72

A Quick Java A Quick Java Swing TutorialSwing Tutorial

Page 73: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

73

IntroductionIntroduction

• Swing – A set of GUI classes– Part of the Java's standard library– Much better than the previous library: AWT

• Abstract Window Toolkit

• Highlights– A rich set of widgets

• Widget: Any GUI element (also called: components) – Contents and shape are separated (MVC support)– Fine-grained control over the behavior and look and feel– Platform independent

• Isolates the programmer from the operating system's GUI

Page 74: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

74

Swing ComponentsSwing Components• Containers

– Contain and manage other components.– Top Level/Internal – Examples: JFrame (Top Level), JScrollPane, JPanel.

• Basic controls– Atomic components – Used for showing ouput and/or getting some input – Inherits JComponent– Examples: JButton, JLabel, JTextArea, JTable, Jlist

• Usually every Swing class extends the corresponding AWT class– For backward-compatibility reasons

Page 75: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

75

My First Swing ProgramMy First Swing Programimport javax.swing.*;import java.awt.BorderLayout;

public class First { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame");

// operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }}

Page 76: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

76

Top Level Containers: JFrameTop Level Containers: JFrame• javax.swing.JFrame:

– Top-level window with a title and a border.– Usually used as a program's main window

Page 77: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

77

More on JFrameMore on JFrame• Made of several layers

• Widgets are added to the Content Pane layer.– Use getContentPane() to obtain it

• Other layers are used for customizing the window's appearence

Page 78: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

78

Top Level Containers: JDialogTop Level Containers: JDialog• javax.swing.JDialog:

– More simple and limited than frames– Typically used for showing a short message on the screen– Also has a border and a title bar– May have an owner

• If the owner is invisible the dialog will also be invisible – Use the static method of JoptionPane to show standard dialog boxes:

JOptionPane.showMessageDialog(null, "4+2=6");

Page 79: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

79

Internal ContainersInternal Containers• Not Top level containers• Can contain other non-top level components• Examples:

– JScrollPane: Provides a scrollable view of its components

– JSplitPane: Separates two components

– JTabbedPane: User chooses whichcomponent to see

Page 80: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

80

Containers - LayoutContainers - Layout

• Each container has a layout manager – Determines the size, location of contained widgets.

• Setting the current layout of a container:void setLayout(LayoutManager lm)

• LayoutManager implementing classes:– BorderLayout– BoxLayout– FlowLayout– GridLayout

Page 81: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

81

Containers - LayoutContainers - Layout

Page 82: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

82

Swing ComponentsSwing Components

Page 83: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

83

Swing ComponentsSwing Components

Page 84: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

84

First Swing Program RevisitedFirst Swing Program Revisited

import javax.swing.*;import java.awt.BorderLayout;

public class First { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame");

// operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }}

Create a frame

Create a text label

Add the label to the content pane

Choose the border layout

Specify CENTER as the layout position

Page 85: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

85

InputInput• 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

Page 86: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

86

Events, ListenersEvents, 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

Page 87: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

87

Events, Listeners (cont.)Events, Listeners (cont.)

• A listener is an object that implements a listener interface

• If we need to react to an event (on a certain widget) we register a listener object with that widget

• E.g.: addActionListener() registers an action listener with its receiver:

JButton button = new JButton(); ActionListener listener = ...; button.addActionListener(listener);

• When an event occurs, all registered listeners are notified– The appropriate listener method (e.g: actionPerformed()) is invoked – An object describing the event is passed as a parameter

Page 88: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

88

Event Handling Demo: GUIEvent Handling Demo: GUI

Page 89: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

89

Event Handling Demo: CodeEvent Handling Demo: Codeimport javax.swing.*;import java.awt.*;import java.awt.event.*;

public class Events implements ActionListener { public Events() { JFrame frame = new JFrame("Events"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Click me!"); b.addActionListener(this); frame.getContentPane().add(b); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Thank you"); } public static void main(String[] args) { new Events(); } }

Page 90: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Example of using RadioButtons

• From Roseindia.net

Page 91: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

• import javax.swing.*;• import java.awt.*;• import java.awt.event.*;

• public class SelectRadioButton{• JLabel label;

• public SelectRadioButton(){• JFrame frame = new JFrame("Radio button selection");• JRadioButton first = new JRadioButton("First");• JRadioButton second = new JRadioButton("Second");• JRadioButton third = new JRadioButton("Third");• JRadioButton fourth = new JRadioButton("Fourth");• JRadioButton fifth = new JRadioButton("Fifth");•

Page 92: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

• JPanel panel = new JPanel();• panel.add(first);• panel.add(second);• panel.add(third);• panel.add(fourth);• panel.add(fifth);• ButtonGroup bg = new ButtonGroup();• bg.add(first);• bg.add(second);• bg.add(third);• bg.add(fourth);• bg.add(fifth);

Page 93: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

• first.addActionListener(new MyAction());• second.addActionListener(new MyAction());• third.addActionListener(new MyAction());• fourth.addActionListener(new MyAction());• fifth.addActionListener(new MyAction());• label = new JLabel("Roseindia.net");• frame.add(panel, BorderLayout.NORTH);• frame.add(label, BorderLayout.CENTER);• frame.setSize(400, 400);• frame.setVisible(true);• frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);• }

Page 94: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

• public class MyAction implements ActionListener{• public void actionPerformed(ActionEvent e){• label.setText(e.getActionCommand());• JOptionPane.showMessageDialog(null,"This is the " +

e.getActionCommand() + • " radio button.");• }• }• public static void main(String[] args){• SelectRadioButton sr = new SelectRadioButton();• }• }

Page 95: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Notes

• Label.SetText assigns text to the label.• e.getActionCommand(); gets the

text(command) from the control• label.setText(e.getActionCommand());• Assigns the label text the value from

e.getActionCommand which is the text associaited with the control.

Page 96: String Class String Class in package java.lang String is a class not a primitive data type String constants can be created using a traditional shorthand

Notes 2

• ActionListener etc are examples of Java Interfaces

• These are class definitions with blank method declarations.

• This allows the user to define their own methods

• We will see these next week.