SlideShare a Scribd company logo
1 of 44
Download to read offline
Lecture 7
GUIs and Inheritance
Getting even GUIer
Plan
▪ More GUIs
– GUI components
▪ Background
– Inheritance
Plan
▪ Review:
– Created a frame – JFrame class
JFrame jFrame = new JFrame();
jFrame.setTitle("GUIs are awesome!");
jFrame.setSize(400,300);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
Plan
▪ Review:
– Created a frame – JFrame class
– Accessed the content pane of the frame – Container class
Container CP = jFrame.getContentPane();
Plan
▪ Review:
– Created a frame – JFrame class
– Accessed the content pane of the frame – Container class
– Created a pop-up window to give message to the user –
JOptionPane class
JOptionPane.showMessageDialog(jFrame, "Java is so much fun!");
JOptionPane.showMessageDialog(null, "Java is so much fun!");
Plan
▪ Review:
– Created a frame – JFrame class
– Accessed the content pane of the frame – Container class
– Created a pop-up window to give message to the user –
JOptionPane class
– Created a pop-up window to get data from the user -
JOptionPane
String s = JOptionPane.showInputDialog(jFrame, "What year were
you born in?");
int i = Integer.parseInt(s);
Plan
▪ Review:
– Created a frame – JFrame class
– Accessed the content pane of the frame – Container class
– Created a pop-up window to give message to the user –
JOptionPane class
– Created a pop-up window to get data from the user –
JOptionPane
▪ Look at components that we can add to the content
pane: JButton, JLabel, JTextField…
▪ Inheritance and Interfaces
Adding basic components
GUIS
▪ Many different types of GUI objects
▪ https://web.mit.edu/6.005/www/sp14/psets/ps4/java-
6-tutorial/components.html - good reference
GUI components
Pushbutton.
▪ JButton – from the javax.swing package
▪ The text passed to the constructor is the text inside the
button.
▪ Also generates an action event – will get to later.
JButton okButton = new JButton("OK");
JButton cancelButton = new JButton("Cancel");
JButton acceptButton = new JButton("Accept", acceptIcon);
Name of the button Text on the button
GUI components
Text, images
▪ JLabel – from the javax.swing package
▪ The text passed to the constructor is the text inside the
Label.
▪ Can also specify an ImageIcon object which can contain
an image.
▪ No action event.
JLabel myText = new JLabel("Welcome to my program!");
GUI components
Images
▪ ImageIcon – from the java.swing package
▪ Used to hold an image.
▪ Can then be passed to constructor of JLabel or JButton
to actually show the image.
▪ No action event.
ImageIcon myIm = new ImageIcon("SpongeBob.jpg");
JLabel myLabel = new JLabel(myIm);
GUI components
Text input
▪ JTextField – from the java.swing package
▪ Allows user to enter a line of text.
▪ Constructor: initial text, the width in characters or both
▪ Has action event when user hits Enter key while it is active
(has blinking vertical line)
JTextField myTF = new JTextField();
JTextField myTF = new JTextField("Please enter your text here");
JTextField myTF = new JTextField("Please enter your text here", 40);
GUI components
Text input
▪ JTextArea – from the java.swing package
▪ Allows user to enter multiple lines of text.
▪ Constructor: Default text, rows and width
▪ Set the size of the object:
JTextArea myTA = new JTextArea();
JTextArea myTA = new JTextArea("Please enter your text here");
JTextArea myTA = new JTextArea("Please enter your text here", 5 , 30);
myTA.setColumns(30);
myTA.setRows(10);
GUI components
Drop down box
▪ JComboBox – from the java.swing package
▪ Gives the user options that they can choose from a
drop down box.
▪ Constructor: String array of choices
▪ Can also set the top box to be editable or not.
String[] times = {"10:00", "10:30", "11:00", "11:30", "12:00"};
JComboBox myCB = new JComboBox(times);
myCB.setEditable(true);
Inheritance and Interfaces
Inheritance
▪ In order to understand some GUI concepts, we have to
look at some inheritance concepts.
▪ Inheritance is not part of the syllabus of this course and
it will not be directly examined.
▪ But you need to understand it in order to understand
some GUI concepts.
Inheritance
▪ Let’s imagine we’ve created a class called Student
public class Student {
String name;
long studentNo;
int YearOfStudy;
Student(){
System.out.println("Student constructor.");
}
void MethodA() {
System.out.println("MethodA from Student.");
}
}
Inheritance
▪ Let’s imagine we’ve created a class called Student
▪ Now lets imagine that we want to make some other
classes based on this class:
– eg. PGStudent or UGStudent or PTstudent
▪ These classes will have a lot in common with Student
but they will have things that are unique to those
classes as well.
Inheritance
▪ We can create a class from
another class.
▪ We use the keyword:
extends
public class UGStudent extends Student{
String[] ListOfCourses;
float[] ListOfMarks;
float ReturnAveMark() {...}
}
public class PGStudent extends Student {
String Supervisor;
String DegreeType;
void SubmitThesis() {}
}
Inheritance
One class acquires the
members of another
class.
Inheritance
▪ The class we are inheriting from is called the superclass.
▪ The class that inherits is called the subclass.
Student
UGStudent PGStudent
Superclass
Subclass
Inheritance
▪ We can build a hierarchy of classes:
UniversityMember
Staff
Administrative
Academic
Technical
Student
UGStudent PGStudent
Inheritance
▪ Subclasses inherit the attributes and methods of the
superclasses
▪ Objects created from subclasses will have the attributes
and methods of the superclasses.
▪ They can then add their own attributes and methods.
Inheritance
public class Student {
String name;
long studentNo;
int YearOfStudy;
Student(){...}
void MethodA() {...}
}
public class UGStudent extends Student{
String[] ListOfCourses;
float[] ListOfMarks;
float ReturnAveMark() {...}
}
Inheritance
public class Student {
String name;
long studentNo;
int YearOfStudy;
Student(){...}
void MethodA() {...}
}
public class UGStudent extends Student{
String[] ListOfCourses;
float[] ListOfMarks;
float ReturnAveMark() {...}
}
This code isn’t
really here, but
these members
of Student are
available to
UGStudent.
Inheritance
▪ So if we have: public class UGStudent extends Student{
String[] ListOfCourses;
float[] ListOfMarks;
float ReturnAveMark() {...}
}
public class Student {
String name;
long studentNo;
int YearOfStudy;
Student(){
System.out.println("Student constructor.");
}
void MethodA() {
System.out.println("MethodA from Student.");
}
}
Inheritance
▪ Then in the main class, we can say:
PGStudent a = new PGStudent();
a.MethodA();
▪ Calling a method defined in the superclass from an object of the
subclass.
▪ The methods and attributes of the superclass are automatically
part of the subclass.
Object of the subclass
Method from the superclass
Inheritance
▪ We can also create objects of a subclass and assign it to
the superclass.
– An object declared to be of superclass A can refer to an instance
of subclass B or C.
– An object declared to be of class Student can reference to an
instance of UGStudent or PGStudent
Student a = new PGStudent();
PGStudent a = new PGStudent();
Object from the subclass
Assigned to superclass
Interfaces
▪ We have seen how one class extends another class.
▪ A related concept is implementing an interface.
▪ interface : like a class
– It has methods, attributes etc…
▪ …but…
– We don’t give any details i.e. no bodies to any method.
▪ So an interface just gives what a class would look
like to the outside, without giving any details.
Interfaces
▪ If we have an interface we can implement it.
▪ We say that a class implements an interface if it
gives the method bodies to all the methods in the
interface.
▪ We must write all the methods in an interface.
▪ We can write more methods that are not in the
interface.
Interfaces
▪ So if we have:
interface MyInterface {
void MethodA();
void MethodB();
}
public class MyClass implements MyInterface{
public void MethodA() {
System.out.println(“My Method A");
}
public void MethodB() {
System.out.println(“My Method B");
}
}
• We can implement this as follows:
Interfaces
▪ Interfaces are helpful because I know that if MyClass
implements MyInterface, then I know that MyClass
must have:
– a method void MethodA()
– a method void MethodB()
▪ So if I create an object MyObject from a class that
implements MyInterface, I know I will be able to say
MyObject.MethodA()
Inheritance and Interfaces
▪ Inheritance gives us a way of creating classes from
other classes
▪ Interfaces give us a way of defining what methods a
class should have without defining the method.
Back to GUIs
Back to GUIs
▪ Now lets bring this back to GUIs…
▪ We have seen how the things that make a window are
objects of various GUI classes (like JFrame, JOptionPane,
JButton …)
▪ So far, we have created an object from these classes
and then changed their attributes.
▪ Instead we can inherit from these classes are create
out own, more specialized classes
- in particular JFrame
GUIs
import javax.swing.*;
public class MyFrame extends JFrame{
MyFrame(){
setTitle("My Frame.");
setSize(200,200);
setLocation(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
▪ Notice how this class calls the methods
setTitle() and setSize() – how can it do this?
JFrame
MyFrame
GUIs
▪ Now we can create objects of the
MyFrame class that we have just written:
public class L7 {
public static void main(String[] args) {
MyFrame mf = new MyFrame();
mf.setVisible(true);
}
}
We didn’t write this method – it was
inherited from the JFrame class, so it
is past of our MyFrame, because
MyFrame is a subclass of JFrame.
GUIs
public class MyBlueFrame extends JFrame{
public static void main(String[] args) {
MyBlueFrame mbf = new MyBlueFrame();
}
}
• Go one step further…
• We can even write this as the main class and have a main
method as one of its methods.
– Will have a main method
– This class should extend JFrame class
GUIs
MyBlueFrame(String title){
setTitle(title);
setSize(500,500);
setLocation(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
• Let’s write a constructor that does the stuff we usually do
with frames…
• Why setTitle() and not frame.setTitle()?
• Because setTitle() is an object method that is a member
of JFrame objects – objects created from our class are
JFrame objects!
GUIs
• Let’s overload this constructor with a version that takes in
the size of the frame.
MyBlueFrame(String title, int x, int y){
setTitle(title);
setSize(x,y);
setLocation(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
• Now let’s say we want to set limits on the size of
the frame – these should be accessible by the user
• Let’s use class constants to do this!
GUIs
public static int MAX_X = 250, MAX_Y = 250;
public static void main(String[] args) {...}
MyBlueFrame(String title, int x, int y){
setTitle(title);
if (x > MAX_X)
x = MAX_X;
if (y > MAX_Y)
y = MAX_Y;
setSize(x, y);
setLocation(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
GUIs
public static int MAX_X = 250, MAX_Y = 250;
public static void main(String[] args) {...}
MyBlueFrame(String title, int x, int y){
setTitle(title);
setSize(x > MAX_X ? MAX_X : x, y > MAX_Y ? MAX_Y : y);
setLocation(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
• These are class constants
• We can use MAX_X instead of MyBlueFrame.MAX_X
because we are inside the MyBlueFrame class.
GUIs
void SetBackgroundToBlue() {
Container cp = getContentPane();
cp.setBackground(Color.BLUE);
}
• Let’s add a function that changes the background to blue…
• Why getContentPane() and not frame.getContentPane()?
• Because getContentPane() is an object method that is a
member of JFrame objects – objects created from our class
are JFrame objects!
GUIs
public class MyBlueFrame extends JFrame{
public static void main(String[] args) {
MyBlueFrame mbf = new MyBlueFrame("My blue frame");
mbf.SetBackgroundToBlue();
mbf.setVisible(true);
}
}
• In the main method, should I use mbf.SetBackgroundToBlue()
or SetBackgroundToBlue()?
• Is this an object method or a class method?
• Does this method belong to the class or does it only
correspond to a particular object?
• Object method!

More Related Content

Similar to Lecture 7.pdf

Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
rd1742
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdf
irshadkumar3
 

Similar to Lecture 7.pdf (20)

Inheritance
InheritanceInheritance
Inheritance
 
Static keyword.pptx
Static keyword.pptxStatic keyword.pptx
Static keyword.pptx
 
Lecture 4 part 1.pdf
Lecture 4 part 1.pdfLecture 4 part 1.pdf
Lecture 4 part 1.pdf
 
Customise Odoo addons modules
Customise Odoo addons modulesCustomise Odoo addons modules
Customise Odoo addons modules
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
04inherit
04inherit04inherit
04inherit
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Java OO Revisited
Java OO RevisitedJava OO Revisited
Java OO Revisited
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
SWING.pptx
SWING.pptxSWING.pptx
SWING.pptx
 
Hello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdfHello. Im currently working on the last section to my assignment a.pdf
Hello. Im currently working on the last section to my assignment a.pdf
 
Java Quiz Application .pdf
Java Quiz Application .pdfJava Quiz Application .pdf
Java Quiz Application .pdf
 
Logic and Coding of Java Interfaces & Swing Applications
Logic and Coding of Java Interfaces & Swing ApplicationsLogic and Coding of Java Interfaces & Swing Applications
Logic and Coding of Java Interfaces & Swing Applications
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 

More from SakhilejasonMsibi (7)

Lecture 6.pdf
Lecture 6.pdfLecture 6.pdf
Lecture 6.pdf
 
Lecture 4 part 2.pdf
Lecture 4 part 2.pdfLecture 4 part 2.pdf
Lecture 4 part 2.pdf
 
Lecture 11.pdf
Lecture 11.pdfLecture 11.pdf
Lecture 11.pdf
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Lecture 9.pdf
Lecture 9.pdfLecture 9.pdf
Lecture 9.pdf
 
Lecture 10.pdf
Lecture 10.pdfLecture 10.pdf
Lecture 10.pdf
 
Lecture1.pdf
Lecture1.pdfLecture1.pdf
Lecture1.pdf
 

Recently uploaded

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 

Recently uploaded (20)

High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 

Lecture 7.pdf

  • 1. Lecture 7 GUIs and Inheritance Getting even GUIer
  • 2. Plan ▪ More GUIs – GUI components ▪ Background – Inheritance
  • 3. Plan ▪ Review: – Created a frame – JFrame class JFrame jFrame = new JFrame(); jFrame.setTitle("GUIs are awesome!"); jFrame.setSize(400,300); jFrame.setVisible(true); jFrame.setDefaultCloseOperation(jFrame.EXIT_ON_CLOSE);
  • 4. Plan ▪ Review: – Created a frame – JFrame class – Accessed the content pane of the frame – Container class Container CP = jFrame.getContentPane();
  • 5. Plan ▪ Review: – Created a frame – JFrame class – Accessed the content pane of the frame – Container class – Created a pop-up window to give message to the user – JOptionPane class JOptionPane.showMessageDialog(jFrame, "Java is so much fun!"); JOptionPane.showMessageDialog(null, "Java is so much fun!");
  • 6. Plan ▪ Review: – Created a frame – JFrame class – Accessed the content pane of the frame – Container class – Created a pop-up window to give message to the user – JOptionPane class – Created a pop-up window to get data from the user - JOptionPane String s = JOptionPane.showInputDialog(jFrame, "What year were you born in?"); int i = Integer.parseInt(s);
  • 7. Plan ▪ Review: – Created a frame – JFrame class – Accessed the content pane of the frame – Container class – Created a pop-up window to give message to the user – JOptionPane class – Created a pop-up window to get data from the user – JOptionPane ▪ Look at components that we can add to the content pane: JButton, JLabel, JTextField… ▪ Inheritance and Interfaces
  • 9. GUIS ▪ Many different types of GUI objects ▪ https://web.mit.edu/6.005/www/sp14/psets/ps4/java- 6-tutorial/components.html - good reference
  • 10. GUI components Pushbutton. ▪ JButton – from the javax.swing package ▪ The text passed to the constructor is the text inside the button. ▪ Also generates an action event – will get to later. JButton okButton = new JButton("OK"); JButton cancelButton = new JButton("Cancel"); JButton acceptButton = new JButton("Accept", acceptIcon); Name of the button Text on the button
  • 11. GUI components Text, images ▪ JLabel – from the javax.swing package ▪ The text passed to the constructor is the text inside the Label. ▪ Can also specify an ImageIcon object which can contain an image. ▪ No action event. JLabel myText = new JLabel("Welcome to my program!");
  • 12. GUI components Images ▪ ImageIcon – from the java.swing package ▪ Used to hold an image. ▪ Can then be passed to constructor of JLabel or JButton to actually show the image. ▪ No action event. ImageIcon myIm = new ImageIcon("SpongeBob.jpg"); JLabel myLabel = new JLabel(myIm);
  • 13. GUI components Text input ▪ JTextField – from the java.swing package ▪ Allows user to enter a line of text. ▪ Constructor: initial text, the width in characters or both ▪ Has action event when user hits Enter key while it is active (has blinking vertical line) JTextField myTF = new JTextField(); JTextField myTF = new JTextField("Please enter your text here"); JTextField myTF = new JTextField("Please enter your text here", 40);
  • 14. GUI components Text input ▪ JTextArea – from the java.swing package ▪ Allows user to enter multiple lines of text. ▪ Constructor: Default text, rows and width ▪ Set the size of the object: JTextArea myTA = new JTextArea(); JTextArea myTA = new JTextArea("Please enter your text here"); JTextArea myTA = new JTextArea("Please enter your text here", 5 , 30); myTA.setColumns(30); myTA.setRows(10);
  • 15. GUI components Drop down box ▪ JComboBox – from the java.swing package ▪ Gives the user options that they can choose from a drop down box. ▪ Constructor: String array of choices ▪ Can also set the top box to be editable or not. String[] times = {"10:00", "10:30", "11:00", "11:30", "12:00"}; JComboBox myCB = new JComboBox(times); myCB.setEditable(true);
  • 17. Inheritance ▪ In order to understand some GUI concepts, we have to look at some inheritance concepts. ▪ Inheritance is not part of the syllabus of this course and it will not be directly examined. ▪ But you need to understand it in order to understand some GUI concepts.
  • 18. Inheritance ▪ Let’s imagine we’ve created a class called Student public class Student { String name; long studentNo; int YearOfStudy; Student(){ System.out.println("Student constructor."); } void MethodA() { System.out.println("MethodA from Student."); } }
  • 19. Inheritance ▪ Let’s imagine we’ve created a class called Student ▪ Now lets imagine that we want to make some other classes based on this class: – eg. PGStudent or UGStudent or PTstudent ▪ These classes will have a lot in common with Student but they will have things that are unique to those classes as well.
  • 20. Inheritance ▪ We can create a class from another class. ▪ We use the keyword: extends public class UGStudent extends Student{ String[] ListOfCourses; float[] ListOfMarks; float ReturnAveMark() {...} } public class PGStudent extends Student { String Supervisor; String DegreeType; void SubmitThesis() {} } Inheritance One class acquires the members of another class.
  • 21. Inheritance ▪ The class we are inheriting from is called the superclass. ▪ The class that inherits is called the subclass. Student UGStudent PGStudent Superclass Subclass
  • 22. Inheritance ▪ We can build a hierarchy of classes: UniversityMember Staff Administrative Academic Technical Student UGStudent PGStudent
  • 23. Inheritance ▪ Subclasses inherit the attributes and methods of the superclasses ▪ Objects created from subclasses will have the attributes and methods of the superclasses. ▪ They can then add their own attributes and methods.
  • 24. Inheritance public class Student { String name; long studentNo; int YearOfStudy; Student(){...} void MethodA() {...} } public class UGStudent extends Student{ String[] ListOfCourses; float[] ListOfMarks; float ReturnAveMark() {...} }
  • 25. Inheritance public class Student { String name; long studentNo; int YearOfStudy; Student(){...} void MethodA() {...} } public class UGStudent extends Student{ String[] ListOfCourses; float[] ListOfMarks; float ReturnAveMark() {...} } This code isn’t really here, but these members of Student are available to UGStudent.
  • 26. Inheritance ▪ So if we have: public class UGStudent extends Student{ String[] ListOfCourses; float[] ListOfMarks; float ReturnAveMark() {...} } public class Student { String name; long studentNo; int YearOfStudy; Student(){ System.out.println("Student constructor."); } void MethodA() { System.out.println("MethodA from Student."); } }
  • 27. Inheritance ▪ Then in the main class, we can say: PGStudent a = new PGStudent(); a.MethodA(); ▪ Calling a method defined in the superclass from an object of the subclass. ▪ The methods and attributes of the superclass are automatically part of the subclass. Object of the subclass Method from the superclass
  • 28. Inheritance ▪ We can also create objects of a subclass and assign it to the superclass. – An object declared to be of superclass A can refer to an instance of subclass B or C. – An object declared to be of class Student can reference to an instance of UGStudent or PGStudent Student a = new PGStudent(); PGStudent a = new PGStudent(); Object from the subclass Assigned to superclass
  • 29. Interfaces ▪ We have seen how one class extends another class. ▪ A related concept is implementing an interface. ▪ interface : like a class – It has methods, attributes etc… ▪ …but… – We don’t give any details i.e. no bodies to any method. ▪ So an interface just gives what a class would look like to the outside, without giving any details.
  • 30. Interfaces ▪ If we have an interface we can implement it. ▪ We say that a class implements an interface if it gives the method bodies to all the methods in the interface. ▪ We must write all the methods in an interface. ▪ We can write more methods that are not in the interface.
  • 31. Interfaces ▪ So if we have: interface MyInterface { void MethodA(); void MethodB(); } public class MyClass implements MyInterface{ public void MethodA() { System.out.println(“My Method A"); } public void MethodB() { System.out.println(“My Method B"); } } • We can implement this as follows:
  • 32. Interfaces ▪ Interfaces are helpful because I know that if MyClass implements MyInterface, then I know that MyClass must have: – a method void MethodA() – a method void MethodB() ▪ So if I create an object MyObject from a class that implements MyInterface, I know I will be able to say MyObject.MethodA()
  • 33. Inheritance and Interfaces ▪ Inheritance gives us a way of creating classes from other classes ▪ Interfaces give us a way of defining what methods a class should have without defining the method.
  • 35. Back to GUIs ▪ Now lets bring this back to GUIs… ▪ We have seen how the things that make a window are objects of various GUI classes (like JFrame, JOptionPane, JButton …) ▪ So far, we have created an object from these classes and then changed their attributes. ▪ Instead we can inherit from these classes are create out own, more specialized classes - in particular JFrame
  • 36. GUIs import javax.swing.*; public class MyFrame extends JFrame{ MyFrame(){ setTitle("My Frame."); setSize(200,200); setLocation(300,300); setDefaultCloseOperation(EXIT_ON_CLOSE); } } ▪ Notice how this class calls the methods setTitle() and setSize() – how can it do this? JFrame MyFrame
  • 37. GUIs ▪ Now we can create objects of the MyFrame class that we have just written: public class L7 { public static void main(String[] args) { MyFrame mf = new MyFrame(); mf.setVisible(true); } } We didn’t write this method – it was inherited from the JFrame class, so it is past of our MyFrame, because MyFrame is a subclass of JFrame.
  • 38. GUIs public class MyBlueFrame extends JFrame{ public static void main(String[] args) { MyBlueFrame mbf = new MyBlueFrame(); } } • Go one step further… • We can even write this as the main class and have a main method as one of its methods. – Will have a main method – This class should extend JFrame class
  • 39. GUIs MyBlueFrame(String title){ setTitle(title); setSize(500,500); setLocation(300,300); setDefaultCloseOperation(EXIT_ON_CLOSE); } • Let’s write a constructor that does the stuff we usually do with frames… • Why setTitle() and not frame.setTitle()? • Because setTitle() is an object method that is a member of JFrame objects – objects created from our class are JFrame objects!
  • 40. GUIs • Let’s overload this constructor with a version that takes in the size of the frame. MyBlueFrame(String title, int x, int y){ setTitle(title); setSize(x,y); setLocation(300,300); setDefaultCloseOperation(EXIT_ON_CLOSE); } • Now let’s say we want to set limits on the size of the frame – these should be accessible by the user • Let’s use class constants to do this!
  • 41. GUIs public static int MAX_X = 250, MAX_Y = 250; public static void main(String[] args) {...} MyBlueFrame(String title, int x, int y){ setTitle(title); if (x > MAX_X) x = MAX_X; if (y > MAX_Y) y = MAX_Y; setSize(x, y); setLocation(300,300); setDefaultCloseOperation(EXIT_ON_CLOSE); }
  • 42. GUIs public static int MAX_X = 250, MAX_Y = 250; public static void main(String[] args) {...} MyBlueFrame(String title, int x, int y){ setTitle(title); setSize(x > MAX_X ? MAX_X : x, y > MAX_Y ? MAX_Y : y); setLocation(300,300); setDefaultCloseOperation(EXIT_ON_CLOSE); } • These are class constants • We can use MAX_X instead of MyBlueFrame.MAX_X because we are inside the MyBlueFrame class.
  • 43. GUIs void SetBackgroundToBlue() { Container cp = getContentPane(); cp.setBackground(Color.BLUE); } • Let’s add a function that changes the background to blue… • Why getContentPane() and not frame.getContentPane()? • Because getContentPane() is an object method that is a member of JFrame objects – objects created from our class are JFrame objects!
  • 44. GUIs public class MyBlueFrame extends JFrame{ public static void main(String[] args) { MyBlueFrame mbf = new MyBlueFrame("My blue frame"); mbf.SetBackgroundToBlue(); mbf.setVisible(true); } } • In the main method, should I use mbf.SetBackgroundToBlue() or SetBackgroundToBlue()? • Is this an object method or a class method? • Does this method belong to the class or does it only correspond to a particular object? • Object method!