slides - Angus Forbes

Download Report

Transcript slides - Angus Forbes

CS 5JA Introduction to Java
Two weeks left!
Final exam is on Thursday, December 6th during the last class.
- will cover everything on the first midterm, and everything since then: arrays, multidimensional arrays, ArrayLists, Strings, various things to do with methods,
various things to do with classes and objects, encapsulation, inheritance, and
polymorphism.
- study session to be led by Bita on Sunday to help you prepare for thhe final exam.
One final homework with two parts.
Part 1: You will create a simple program that uses polymorphism
Part 2: You will make a simple user-interface that loads and then manipulates an
image.
This assignment will be due on Wednesday during finals week. Please start early!
CS 5JA Introduction to Java
A simple but real OO example
Last class I talked about inheritance and polymorphism. I used a kind of
generic example of Birds and chirps.
Here’s a simple example that could conceivably be used with the Poetry
Generator.
The assignment asks you to encode the parts of speech of particular
sentences so that you can mimic the grammatical structure of a poem.
Because you might want to add lots of different types of sentences, and
also make it so that other people could easily add other sentences, you
might consider making your sentences into Objects. In particular, since
creating sentences has more less the same logic for all sentences, it
might make sense to put the basic functionality in a superclass, and
extend the specific functionality for a sentence into a subclass.
CS 5JA Introduction to Java
A simple but real OO example
Base class:
Sentence:
common data needed by all Sentences:
ability to get random words from the different word lists
placeholder for common method to create a sentence.
Inherited classes:
special method for deciding on the types of words to get and their
order.
special method for getting punctuation, stylistic additions, etc.
CS 5JA Introduction to Java
Our base class:
public class Sentence
{
public String getRandomWord(List<String> wordList)
{
int index = (int) (Math.random() * wordList.size());
return wordList.get(index);
}
public String createSentence()
{
return “”; //this is just the base class. We can change this so that it
has default functionality
}
}
CS 5JA Introduction to Java
An extended class
public EECummingsSentence extends Sentence
{
public EECummingsSentence(PoetryGenerator generator)
{
this.generator = generator;
}
public String getRandomPunctuationMark()
{
//logic to return a & or a ! or a %-- e.e. cummings style
}
public String createSentence()
{
String sentence = “”;
sentence += getRandomWord(generator.nounList).toLowerCase();
sentence += “ ” + getRandomPunctuationMark();
sentence += “ “ + getRandomWord(generator.adjList).toLowerCase();
return sentence;
}
}
CS 5JA Introduction to Java
Another extended class
public EmilyDickinsonSentence extends Sentence
{
public EmilyDickinsonSentence(PoetryGenerator generator)
{
this.generator = generator;
}
public String createSentence()
{
String sentence = “”;
sentence += “The “
sentence += getRandomWord(generator.adjList);
sentence += “ “ + getRandomWord(generator.nounList).toUpperCase();
sentence += “ “ + getRandomWord(generator.verbList);
sentence += “ “ + getRandomWord(generator.adverbList);
sentence += “ - - “;
return sentence;
}
}
CS 5JA Introduction to Java
fragment from PoetryGenerator class
List<Sentence> templates = new ArrayList<Sentence>();
templates.add(new EmilyDickinsonSentence(this));
templates.add(new EECummingsSentence(this));
templates.add(new HallmarkCardSentence(this));
String poem = “”;
for (int i = 0; i < templates.size(); i++)
{
Sentence s = templates.get(i);
poem += s.createSentence() + “\n”;
}
System.out.println(poem);
CS 5JA Introduction to Java
fragment from PoetryGenerator class
The program calls the function “createSentence” three times, once for each of the
templates. Each template has a different way of creating the sentences, but
because they are all inherited from the base class “Sentence” we can call it and
be assured that the Polymorphism will make sure and find the appropriate
sentence creating method for us.
So the end result is that we have a weird poem made out of 3 lines, one that sound
like e.e. cummings, one like Emily Dickinson, and one like a greeting card.
String poem = “”;
for (int i = 0; i < templates.size(); i++)
{
Sentence s = templates.get(i);
poem += s.createSentence() + “\n”;
}
System.out.println(poem);
CS 5JA Introduction to Java
abstract methods & classes
If you think about this program we just discussed, you’ll realize that we
never instantiated an actual Sentence object, only objects having a
class type that are derived from the class Sentence.
You also notice that although we defined a method called
“createSentence()” for the base class, we never use it– we always use
the version in the inherited classes.
To make it so that your inherited classes are required to have a particular
method and to make sure that you never accidentally try to instantiate a
base class that doesn’t have any logic in a polymorphic method, you
can define the base class and the relevant methods as abstract.
CS 5JA Introduction to Java
abstract methods & classes
abstract class Sentence
{
public String getRandomWord(List<String> wordList)
{
int index = (int) (Math.random() * wordList.size());
return wordList.get(index);
}
abstract String createSentence();
}
Because the class is defined as abstract, you cannot instantiate it:
CS 5JA Introduction to Java
abstract methods & classes
Because the class is defined as abstract, you cannot instantiate it:
Sentence s = new Sentence(); //returns an error
You can only instantiate the classes that extend from it:
Sentence s = new EECummingsSentence(); //this works!
If you have a method that is similar to all subclasses of the superclass, you
still put it in the superclass and it is available to all the subclasses.
But if there is a method that is different for all the subclasses, then you can
define the method as abstract which will require all the subclasses to
implement it:
abstract String createSentence();
CS 5JA Introduction to Java
instanceof
Polymorphism is great in that it lets us write simpler more organized code. In our
main program we can just loop through all the sentences and know that the
details of the logic are taken care of in the subclasses.
But if there is a particular method or variable that is only available to a subclass,
then we won’t be able get at it if we are referring to it as a type of its base class.
For instance, in the example program we make a List of Sentences and iterate
through them:
List<Sentence> templates = new ArrayList<Sentence>();
templates.add(new EmilyDickinsonSentence(this));
templates.add(new EECummingsSentence(this));
templates.add(new HallmarkCardSentence(this));
for (int i = 0; i < templates.size(); i++)
{
Sentence s = templates.get(i);
System.out.println(s.createSentence() + “\n”);
}
CS 5JA Introduction to Java
instanceof
But since our List only holds sentences (ie the superclass), there is no way to grab
specific variables unique to the subclass. Indeed, this is the point of objectoriented programming– you hide the implementation details of each specific
subclass and can focus on the more general logic.
List<Sentence> templates = new ArrayList<Sentence>();
templates.add(new EmilyDickinsonSentence(this));
templates.add(new EECummingsSentence(this));
templates.add(new HallmarkCardSentence(this));
for (int i = 0; i < templates.size(); i++)
{
Sentence s = templates.get(i);
if (s instanceof EECummingsSentence)
{
System.out.println(“this is an EECummings line of poetry!” + “\n”);
}
}
CS 5JA Introduction to Java
Loading an image
public void loadImage(String filename)
{
Image img = null;
File inputFile = new File(filename);
try
{
img = ImageIO.read(inputFile);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
CS 5JA Introduction to Java
Saving an image
public void saveImage(String filename)
{
BufferedImage img = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_RGB);
Graphics g = img.createGraphics();
paintComponent(g);
//or you can draw directly on it, since you have a Graphics object
//ie. g.setColor(new Color.RED);
//g.drawRect(10, 10, 50, 50); //etc
try
{
File outputFile = new File(filename);
ImageIO.write(output, "JPG", outputFile);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
CS 5JA Introduction to Java
User Interfaces : Swing
Swing is the name of Java’s user interface toolkit. You’ve already seen
JFrame and JPanel. But there is also a bunch of other things:
JButton
JSlider
JTextField
JFileChooser
JColorChooser
JMenuBar
JSplitPane
JPopupMenu
JProgressBar
etc (show swingset...)
CS 5JA Introduction to Java
User Interfaces : Swing
Just as we did with JPanel, we can take advantage of the built-in
functionality of the “widgets”, and also extend them to do extra things,
or to make them look different, etc.
For the homework assignment you won’t have to extend any of these
widgets (except JPanel) but you’ll have to learn how to add listeners to
them.
A listener is a section of code that is invoked in response to a particular
user action. You’ve already played with the mouse listeners and the
keyboard listener. The different swing widgets also have their own
listeners that respond to different actions. Thus they are called
ActionListeners.
CS 5JA Introduction to Java
User Interfaces : Swing
An ActionListener is an interface, and it requires that you have a method
called with this function signature:
public void actionPerformed(ActionEvent ae)
Since objects can listen for multiple actions, you can query the ActionEvent
to see which one of them actually happened.
If you don’t care about the specific action but just want to know that any
action has occured, you can ignore the ActionEvent.
CS 5JA Introduction to Java
User Interfaces : Swing
JButton myButton = new JButton(“press me!”);
myButton.addActionListener(new MyButtonListener());
***
public class MyButtonListener extends ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println(“Hey you pressed me!!!”);
}
}
Because this code is so simple, instead of writing a whole new file, you can
just describe it in an inner class. See code....
CS 5JA Introduction to Java
Last Class
We talked again about polymorphism.
We mentioned the abstract keyword and why you might use it.
We also talked about the instanceof keyword, which can help you determine the
subclass of an object when is stored in a variable of its superclass.
I also showed you a program that had a very simple user interface that let you
enter words into a JTextField, and write over a photo when you pressed a
JButton.
Pressing the JButton caused the program to store information from the JTextField
into a global variable, and then repaint the screen, using the drawString
method.
That is, we attached a Listener to the JButton, which told the program what actions
to take after the button was pressed.
CS 5JA Introduction to Java
This Class
review Loading/Saving image code
We are going to look at a couple more user-interface widgets.
We are going to look at simple LayoutManagers that help you organize the
different widgets inside your JFrame.
(Bita/ACM Review session)
(Flyer for info about CSmajor)
Let’s look at the homework...
CS 5JA Introduction to Java
Layout managers
When you first create a JFrame, nothing is inside it. You need to explicitly
add components to it. For instance, if you want to add a component
that you can draw on, you call the JPanel (and then override the
paintComponent method).
You can also add components to other components. It is very common to
add a JPanel to a JFrame, and then add user-interface widgets
(JSlider, JTextFields, JButtons, etc) to that JPanel.
You can also add other JPanels to the JPanel and divide up your entire
frame into nested pieces.
Let’s look at a real application and think about the user-interface
components: What user-interface widgets can you find in, say,
PowerPoint? (desktop user interface refers to mouse/keyboard/screen)
CS 5JA Introduction to Java
Layout managers
So there is all this stuff you want to add to your application. How do you
figure out where to put it? What happens to the stuff when you resize
the window? How much space should each of the panels take up?
This layout of your components is handled by different LayoutManagers.
There are lots of them. The most common ones are: FlowLayout, which
tries to layout everything from left to right. BorderLayout, which lets you
choose what “direction” the components should stick to, GridLayout,
which lets you lay things out in tables, GroupLayout, which lets you
easily constrain a series of components to a specific location. Et cetera.
You can look at all the subclasses for LayoutManager in the Javadocs
to see what else is available.
We are going to quickly look at the FlowLayout and the BorderLayout.
CS 5JA Introduction to Java
BorderLayout
To set the LayoutManager to BorderLayout inside your frame or panel, you
call the setLayout method on it:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
public class MyDigitalPainting extends JPanel
{
public MyDigitalPainting(String filename)
{
setLayout(new BorderLayout());
...
}
}
CS 5JA Introduction to Java
BorderLayout
Once the LayoutManger is set, you can then specify where inside the
component you want to put things. BorderLayout lets you attach things
to the CENTER of the panel, or to the NORTH, EAST, SOUTH, or
WEST of the panel.
So, for instance, you might have an application where a document is
visible in the right hand side of the application, and the controls are on
the left side. So you would fist attach the main document to the
CENTER of the JFrame. And then you might attach another JPanel to
hold the controls to the WEST of the JFrame.
Lets say that the controls are three buttons. You could set the
controlPanel’s layout to be a BorderLayout, and then set each button to
be NORTH, CENTER, and SOUTH, respecitvely.
CS 5JA Introduction to Java
BorderLayout
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JPanel controlPanel = new JPanel();
JPanel documentPanel = new JPanel();
frame.add(documentPanel, BorderLayout.CENTER);
frame.add(controlPanel, BorderLayout.WEST);
controlPanel.add(new JButton(“1”), BorderLayout.NORTH);
controlPanel.add(new JButton(“2”), BorderLayout.CENTER);
controlPanel.add(new JButton(“3”), BorderLayout.SOUTH);
Now when the main application is resized, the control panel will always stick to the
left while the document panel gets bigger, and the 1st and 3rd button in the
control panel will stick to the top and bottom while the 2nd button gets bigger.
CS 5JA Introduction to Java
FLowLayout
FlowLayout is the default layout. You don’t have to do anything to enable
the flow layout. FlowLayout just tries to add things from left to right.
If you add a bunch of things to the panel it will put them in the order they
were added from. If they don’t fit in the width of the application, it will try
to put it below the previous components.
Flow layout is good for simple things, like adding a set of buttons to a
panel, but you have to be careful because things can get odd when the
application is resized.
CS 5JA Introduction to Java
JButton
Here’s how to make a button:
JButton myButton = new JButton(“press me”);
here’s how to add to a panel using a flow layout manager
myPanel.add(myButton);
here’s how to add it to the bottom of a panel using a border layout
manager
myPanel.add(myButton, BorderLayout.SOUTH);
CS 5JA Introduction to Java
JButton
You probably want something to happen when you press the button, so you can
add an ActionListener to it. For the sake of keeping the code together, we can
use an inner class, which has a weird syntax which we don’t have to get into,
but makes it so you can see the logic of the listener right by where you define
the button.
JButton myButton = new JButton(“press me”);
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(“you pressed me!”);
doSomethingNeat();
repaint();
} });
The one annoying thing about inner classes is that they can’t refer to variables from
the outer class in a regular way. The easiest thing to do in an inner class is
simply call a method from the outer class. For instance, in the above example,
we are assuming that there is a public method in the outer class called
“doSomethingNeat()”;
CS 5JA Introduction to Java
JSlider
Here’s how to make a slider:
JSlider mySlider = new JSlider();
this creates a slider which is horizontal, that returns values between 0 and
100, and stars off right in the middle at 50.
JSlider mySlider2 = new JSlider(JSlider.VERTICAL, 32, 212, 75);
this create a slider which is vertical, that returns values between freezing
and boiling, and starts off at a temperate 75.
here’s how to add it to the right of a panel using a border layout manager
myPanel.add(mySlider2, BorderLayout.EAST);
CS 5JA Introduction to Java
JSlider
You probably want something to happen when you move the slider, so you
can add an ChangeListener to it. We’re also going to use an inner class
JSlider mySlider new JSlider(JSlider.VERTICAL, 32,
212, 75);
mySlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
int temp = source.getValue();
if (temp <= 32) System.out.println(“cold!!!”);
if (temp >= 212) System.out.println(“hot!!!”);
else System.out.println(“just right”);
} });
CS 5JA Introduction to Java
On the test
Questions that make sure you understand the definitions of common terms
& concepts: object, class, inheritance, polymorphism, array, List,
constructor, etc.
Questions that make sure you understand basic syntax: looping through an
multi-dimensional array, using a switch statement, looping through a
List and doing actions based on the value in the List, order of
operations, method signatures, scope of variables, etc
Questions that show you know how to think about organizing your code
into different classes and methods, how to model a problem.
Questions that make sure you can debug obvious errors.
Maybe some tougher extra-credit problems. The test will take 1 hour.