33
Creating a GUI Class Creating a GUI Class An example of class An example of class design using inheritance design using inheritance and interfaces and interfaces

Creating a GUI Class An example of class design using inheritance and interfaces

Embed Size (px)

DESCRIPTION

Our Goal  Program opens up a window like this:  What can we do with it?  can enter numbers into the first and second number boxes  can click the “Calculate” button to put their sum into the result box  can click the “Done” button to end the program

Citation preview

Page 1: Creating a GUI Class An example of class design using inheritance and interfaces

Creating a GUI ClassCreating a GUI Class

An example of class design using An example of class design using inheritance and interfacesinheritance and interfaces

Page 2: Creating a GUI Class An example of class design using inheritance and interfaces

GUI as an Example of I&PGUI as an Example of I&P

The JFrame classThe JFrame class components and layoutcomponents and layout inheriting from JFrameinheriting from JFrame

The ActionListener interfaceThe ActionListener interface adding an action listeneradding an action listener

Page 3: Creating a GUI Class An example of class design using inheritance and interfaces

Our GoalOur Goal

Program opens up a window like this:Program opens up a window like this:

What can we do with it?What can we do with it? can enter numbers into thecan enter numbers into the

first and second number boxesfirst and second number boxes can click the “Calculate” button can click the “Calculate” button

to put their sum into the result boxto put their sum into the result box can click the “Done” button to end the programcan click the “Done” button to end the program

Page 4: Creating a GUI Class An example of class design using inheritance and interfaces

The JFrame ClassThe JFrame Class

javax.swing.JFrame is a window classjavax.swing.JFrame is a window class constructor takes window titleconstructor takes window title need to set its size & make it visibleneed to set its size & make it visible

» otherwise it’s tiny and invisibleotherwise it’s tiny and invisibleJFrame win = new JFrame(“An Empty Window”);JFrame win = new JFrame(“An Empty Window”);win.setSize(300, 200);win.setSize(300, 200);win.setVisible(true);win.setVisible(true);

Page 5: Creating a GUI Class An example of class design using inheritance and interfaces

Window ComponentsWindow Components

Want to add stuff to the windowWant to add stuff to the window labels, text fields, buttonslabels, text fields, buttonswin.add(new JLabel(“Hello!”), BorderLayout.NORTH);win.add(new JLabel(“Hello!”), BorderLayout.NORTH);win.add(new JTextField(), BorderLayout.CENTER);win.add(new JTextField(), BorderLayout.CENTER);win.add(new JButton(“OK”), BorderLayout.SOUTH);win.add(new JButton(“OK”), BorderLayout.SOUTH);

» there are other ways to lay out the windowthere are other ways to lay out the window

Page 6: Creating a GUI Class An example of class design using inheritance and interfaces

Window OperationsWindow Operations

Resizing: JFrame handles thisResizing: JFrame handles this but don’t really need it, so we could get rid of itbut don’t really need it, so we could get rid of it

Entering #s: JTextBox handles thisEntering #s: JTextBox handles this tho’ it will accept non-numbers….tho’ it will accept non-numbers….

Clicking buttons: JButtons “flash”Clicking buttons: JButtons “flash” just do a tiny bit of colour changejust do a tiny bit of colour change nothing else happens!nothing else happens! we will need to do something about that!we will need to do something about that!

Page 7: Creating a GUI Class An example of class design using inheritance and interfaces

PlanPlan

Extend the class JFrameExtend the class JFrame BE the window!BE the window!

» have a main method that just have a main method that just opensopens the window the window

Have constructor set everything upHave constructor set everything up add all the labels/fields/buttons and set them upadd all the labels/fields/buttons and set them up make sure someone is listening to the buttonsmake sure someone is listening to the buttons

» has to be someone who knows how!has to be someone who knows how!» sounds like an interface….sounds like an interface….

Page 8: Creating a GUI Class An example of class design using inheritance and interfaces

New Window ClassesNew Window Classes

Create a class that extends JFrameCreate a class that extends JFrame class is another window classclass is another window classpublic class AdderWindow extends JFrame { … }public class AdderWindow extends JFrame { … }

Use constructor to add labels, buttons, Use constructor to add labels, buttons, etcetc.. laid out in a 5x2 gridlaid out in a 5x2 gridthis.setLayout(new GridLayout(5, 2));this.setLayout(new GridLayout(5, 2)); three fields, two buttons, and three fields, two buttons, and

four labelsfour labels

Page 9: Creating a GUI Class An example of class design using inheritance and interfaces

Instance VariablesInstance Variables

Window needs to track its piecesWindow needs to track its pieces except for the labels – they do nothingexcept for the labels – they do nothingprivate JTextBox firstNumberBox;private JTextBox firstNumberBox;private JTextBox secondNumberBox;private JTextBox secondNumberBox;private JTextBox resultBox;private JTextBox resultBox;private JButton calculateButton;private JButton calculateButton;private JButton doneButton;private JButton doneButton;

Page 10: Creating a GUI Class An example of class design using inheritance and interfaces

Window Constructor TasksWindow Constructor Tasks

Constructor:Constructor: calls parent constructor: calls parent constructor: super(“Adding Numbers”);super(“Adding Numbers”); sets the size and layout: sets the size and layout: setSize(…); setLayout(…);setSize(…); setLayout(…); creates and adds the required elementscreates and adds the required elementsfirstNumberBox = new JTextField();firstNumberBox = new JTextField();……this.add(new JLabel(“First number:”));this.add(new JLabel(“First number:”));this.add(firstNumberBox);this.add(firstNumberBox);…… (also need to “activate” the window–later )(also need to “activate” the window–later )

Page 11: Creating a GUI Class An example of class design using inheritance and interfaces

Program to Open the WindowProgram to Open the Window

Create a variable for the AdderWindowCreate a variable for the AdderWindowAdderWindow d;AdderWindow d;

Create and save the AdderWindow objectCreate and save the AdderWindow objectd = new AdderWindow();d = new AdderWindow();

Make it visibleMake it visibled.setVisible(true);d.setVisible(true);

OrOr we can just create it and make it visible: we can just create it and make it visible:(new AdderWindow()).setVisible(true);(new AdderWindow()).setVisible(true);

Page 12: Creating a GUI Class An example of class design using inheritance and interfaces

Our Window (Inactive)Our Window (Inactive)

Here’s our windowHere’s our window not quite the same as what I showed younot quite the same as what I showed you

Doesn’t do anythingDoesn’t do anything

Page 13: Creating a GUI Class An example of class design using inheritance and interfaces

Getting Some ActionGetting Some Action

Our buttons do nothingOur buttons do nothing» well, they change colour a bit when they’re clickedwell, they change colour a bit when they’re clicked

want them to do somethingwant them to do something Button needs to tell someone it was clickedButton needs to tell someone it was clicked

that someone needs to listen for the clickthat someone needs to listen for the click it needs to know it needs to know howhow to listen for a click to listen for a click

The ActionListener interfaceThe ActionListener interface ““I can listen for events (including clicks)”I can listen for events (including clicks)”

Page 14: Creating a GUI Class An example of class design using inheritance and interfaces

The ActionListener InterfaceThe ActionListener Interface

Knows how to listen for an eventKnows how to listen for an event event sent using actionPerformed methodevent sent using actionPerformed method

Create a new class (“AL”) that implements Create a new class (“AL”) that implements the ActionListener interfacethe ActionListener interfacepublic class AL implements ActionListener { public class AL implements ActionListener { public void actionPerformed(ActionEvent e) { … }public void actionPerformed(ActionEvent e) { … }}} objects of type AL can listen for clicksobjects of type AL can listen for clicks

» and should know what to do when they get themand should know what to do when they get them

Page 15: Creating a GUI Class An example of class design using inheritance and interfaces

Adding ActionListenersAdding ActionListeners

Need to tell the button who’s listeningNeed to tell the button who’s listening then button can send messages to listenersthen button can send messages to listeners

» recall: “sending a message” = “calling a method”recall: “sending a message” = “calling a method” the addActionListener methodthe addActionListener methodActionListener al = new AL();ActionListener al = new AL();calculateButton.addActionListener(al);calculateButton.addActionListener(al); click calculateButton click calculateButton al’s actionPerformed al’s actionPerformed

method gets calledmethod gets called

Page 16: Creating a GUI Class An example of class design using inheritance and interfaces

ProblemProblem

Needs to know how to respond to the clickNeeds to know how to respond to the click needs to get/put numbers from/in text fieldsneeds to get/put numbers from/in text fields needs to have access to those fieldsneeds to have access to those fields those fields are private to our window classthose fields are private to our window class

So?So? cancan add getters/setters in AdderWindow… add getters/setters in AdderWindow… oror we can make the window into the listener! we can make the window into the listener!

» no need to make a no need to make a separateseparate class AL! class AL!

Page 17: Creating a GUI Class An example of class design using inheritance and interfaces

Listening to Own ComponentsListening to Own Components

Have window implement ActionListenerHave window implement ActionListenerpublic class AdderWindow extends JFrame public class AdderWindow extends JFrame

implements ActionListener { … }implements ActionListener { … }» important: extends first, implements afterimportant: extends first, implements after

Add code to constructorAdd code to constructordoneButton.addActionListener(doneButton.addActionListener(thisthis););calculateButton.addActionListener(calculateButton.addActionListener(thisthis););

» says “this window is listening to you”says “this window is listening to you”» remember: “this” is Java for “me” / “I” / “my”remember: “this” is Java for “me” / “I” / “my”

window must now implement actionPerformedwindow must now implement actionPerformed

Page 18: Creating a GUI Class An example of class design using inheritance and interfaces

The actionPerformed MethodThe actionPerformed Method

Argument has information about the eventArgument has information about the event including its “source”: which button it wasincluding its “source”: which button it was

» choose action based on button clickedchoose action based on button clickedpublic void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) { Object clicked = e.getSource();Object clicked = e.getSource(); if (clicked == doneButton) {if (clicked == doneButton) { System.exit(0);System.exit(0); // end program// end program } else if (clicked == calculateButton) {} else if (clicked == calculateButton) { addTheNumbers();addTheNumbers(); // private method// private method }}}}

Page 19: Creating a GUI Class An example of class design using inheritance and interfaces

Adding the NumbersAdding the Numbers

Private method to add and report resultPrivate method to add and report result use getText and Integer.parseInt to read #suse getText and Integer.parseInt to read #s use setText and Integer.toString to show resultuse setText and Integer.toString to show resultprivate void addTheNumbers() {private void addTheNumbers() { int n1, n2;int n1, n2; n1 = Integer.parseInt(firstNumberBox.getText());n1 = Integer.parseInt(firstNumberBox.getText()); n2 = Integer.parseInt(secondNumberBox.getText());n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2));resultBox.setText(Integer.toString(n1 + n2));}}

Page 20: Creating a GUI Class An example of class design using inheritance and interfaces

When Things Go WrongWhen Things Go Wrong

What could go wrong in AdderWindow?What could go wrong in AdderWindow? user might put non-numbers into the boxesuser might put non-numbers into the boxes what happens then?what happens then?

» ““Calculate” button seems to do nothingCalculate” button seems to do nothing» (but there are error messages in output window)(but there are error messages in output window)

what what shouldshould happen then? happen then?» maybe set result field to “Error”?maybe set result field to “Error”?

how can we get that to happen?how can we get that to happen?» let’s look at that error message….let’s look at that error message….

Page 21: Creating a GUI Class An example of class design using inheritance and interfaces

The Error MessagesThe Error Messages

Look at the error messages:Look at the error messages:

““java.lang.NumberFormatException”java.lang.NumberFormatException”» there was a problem with the format of the numbersthere was a problem with the format of the numbers

at … AdderDialog.java:81at … AdderDialog.java:81» line 81 of your programline 81 of your program

java.lang.NumberFormatException: For input string: "ten"at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)at java.lang.Long.parseLong(Long.java:589)at java.lang.Long.parseLong(Long.java:631)at AdderDialog.addTheNumbers(AdderDialog.java:81)at AdderDialog.actionPerformed(AdderDialog.java:73)…

Page 22: Creating a GUI Class An example of class design using inheritance and interfaces

ExceptionsExceptions

Objects that represent problems in programObjects that represent problems in program problems that the program itself might be able to problems that the program itself might be able to

do something aboutdo something about Throw and CatchThrow and Catch

method with problem method with problem throwsthrows the exception the exception» Integer.parseInt threw a NumberFormatExceptionInteger.parseInt threw a NumberFormatException

method that can deal with it will method that can deal with it will catchcatch it it» addTheNumbers can deal with it…addTheNumbers can deal with it…» ……so it needs to be so it needs to be readyready to catch it to catch it

Page 23: Creating a GUI Class An example of class design using inheritance and interfaces

Getting Ready to CatchGetting Ready to Catch

Tell Java you can deal with the exceptionTell Java you can deal with the exception a “catch block” (catch has a a “catch block” (catch has a parameterparameter))catch (WhatKindOfException e) { … }catch (WhatKindOfException e) { … }

» body of catch says what to do for that exceptionbody of catch says what to do for that exception

But need to warn Java it might happenBut need to warn Java it might happen a “try block” (comes a “try block” (comes beforebefore the catch block) the catch block)try { … }try { … }

» must include the command the exception was must include the command the exception was thrown fromthrown from

Page 24: Creating a GUI Class An example of class design using inheritance and interfaces

Dealing with the ProblemDealing with the Problem

TryTry to add the numbers; to add the numbers; catchcatch the exception the exceptionprivate void addTheNumbers() {private void addTheNumbers() { int n1, n2;int n1, n2; try {try { n1 = Integer.parseInt(firstNumberBox.getText());n1 = Integer.parseInt(firstNumberBox.getText()); n2 = Integer.parseInt(secondNumberBox.getText());n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2));resultBox.setText(Integer.toString(n1 + n2)); } catch (NumberFormatException nfe) {} catch (NumberFormatException nfe) { resultBox.setText(“ERROR”);resultBox.setText(“ERROR”); }}}}

» no exception: numbers get added upno exception: numbers get added up» exception: result gets set to “ERROR”exception: result gets set to “ERROR”

Page 25: Creating a GUI Class An example of class design using inheritance and interfaces

Try-Catch ControlTry-Catch Control

Try block contains the code we want to doTry block contains the code we want to do but might throw an exception we can deal withbut might throw an exception we can deal with

Catch block has code to deal with problemCatch block has code to deal with problem says what kind of problem it deals withsays what kind of problem it deals with

» e.g. e.g. NumberFormatExceptionNumberFormatException

If try block works, catch block gets skippedIf try block works, catch block gets skipped If exception happens, jump to catch blockIf exception happens, jump to catch block

remainder of try block gets skippedremainder of try block gets skipped

Page 26: Creating a GUI Class An example of class design using inheritance and interfaces

If There’s No ProblemIf There’s No Problem

Both numbers are OKBoth numbers are OK try {try { n1 = Integer.parseInt(firstNumberBox.getText());n1 = Integer.parseInt(firstNumberBox.getText()); n2 = Integer.parseInt(secondNumberBox.getText());n2 = Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2));resultBox.setText(Integer.toString(n1 + n2)); } } catch (NumberFormatException nfe) {catch (NumberFormatException nfe) { // skipped// skipped resultBox.setText(“ERROR”);resultBox.setText(“ERROR”); }}

100

200

300

?

n1

?

n2100

n1

First number:

Second number:

Result:200

n2

Page 27: Creating a GUI Class An example of class design using inheritance and interfaces

But If There Is a ProblemBut If There Is a Problem

Suppose second number is badSuppose second number is bad try {try { n1 = Integer.parseInt(firstNumberBox.getText());n1 = Integer.parseInt(firstNumberBox.getText()); n2 = n2 = Integer.parseInt(secondNumberBox.getText());Integer.parseInt(secondNumberBox.getText()); resultBox.setText(Integer.toString(n1 + n2));resultBox.setText(Integer.toString(n1 + n2)); // skipped!// skipped! } catch (NumberFormatException nfe) {} catch (NumberFormatException nfe) { resultBox.setText(“ERROR”);resultBox.setText(“ERROR”); }}

100

2oo

ERROR

?

n1

?

n2100

n1

First number:

Second number:

Result:

Page 28: Creating a GUI Class An example of class design using inheritance and interfaces

Input ExceptionsInput Exceptions

Exceptions may happen in reading as wellExceptions may happen in reading as well user enters word where number expecteduser enters word where number expected

» InputMismatchExceptionInputMismatchException file runs out of data earlyfile runs out of data early

» NoSuchElementExceptionNoSuchElementException

Can deal with these as wellCan deal with these as well but don’t need tobut don’t need to

Page 29: Creating a GUI Class An example of class design using inheritance and interfaces

Input ExceptionsInput Exceptions

Read numbers from fileRead numbers from file» may be words in file; may be too few numbersmay be words in file; may be too few numbers

for (int i = 0; i < N; ++i) {for (int i = 0; i < N; ++i) { try {try { arr[i] = in.nextInt();arr[i] = in.nextInt(); } catch (InputMismatchException ime) {} catch (InputMismatchException ime) { arr[i] = -1;arr[i] = -1; // indicates bad input// indicates bad input in.next();in.next(); // skip bad input// skip bad input } catch (NoSuchElementException nse) {} catch (NoSuchElementException nse) { break;break; // no sense trying to read any more!// no sense trying to read any more! }}}}

Page 30: Creating a GUI Class An example of class design using inheritance and interfaces

Multiple Catch BlocksMultiple Catch Blocks

Can have as many catch blocks as you likeCan have as many catch blocks as you like each for a different kind of exceptioneach for a different kind of exception

Catch order Catch order maymay be important be important some exception classes inherit from otherssome exception classes inherit from others

» InputMismatchExcInputMismatchExcnn is ais a NoSuchElementExc NoSuchElementExcnn

» if you ask for an int, and the next thing is a word, if you ask for an int, and the next thing is a word, then there’s no such thing as what you asked forthen there’s no such thing as what you asked for

must put more specific exceptions firstmust put more specific exceptions first» IME must come before NSEEIME must come before NSEE

Page 31: Creating a GUI Class An example of class design using inheritance and interfaces

Never Catch ExceptionNever Catch Exception

Exception is most general exception classException is most general exception class if have if have catch(Exception e)catch(Exception e), it must come last, it must come last it’ll catch it’ll catch anyany exception exception

But DON’T CATCH IT!But DON’T CATCH IT! what could you what could you possiblypossibly do that would deal do that would deal

with with every possible every possible kind of problem?kind of problem?

Page 32: Creating a GUI Class An example of class design using inheritance and interfaces

The throws ClauseThe throws Clause

If your code may throw a checked exception If your code may throw a checked exception and your method doesn’t deal with it, then and your method doesn’t deal with it, then you need to tell Java you you need to tell Java you won’twon’t deal with it deal with it

» that’s what being “checked” meansthat’s what being “checked” means add throws clause to method headeradd throws clause to method headerprivate static Scanner open(String name) private static Scanner open(String name)

throws FileNotFoundException throws FileNotFoundException {{ return new Scanner(new File(name));return new Scanner(new File(name));}}

Page 33: Creating a GUI Class An example of class design using inheritance and interfaces

QuestionsQuestions