Download COMP 14 - Joshua Stough

Document related concepts
no text concepts found
Transcript
COMP 14
Introduction to Programming
Mr. Joshua Stough
April 6, 2005
Monday/Wednesday 11:00-12:15
Peabody Hall 218
Announcements
• Program 6 assigned today
AFS Space
• If you don't have the AFS client on your
laptop, you can still access your AFS
space
• Download and install WS_FTP from
http://shareware.unc.edu
• Remote host: isis.unc.edu
• Remote username: your Onyen
Applets
• Why won't my applet run on my friend's
computer?
– Sun, creator of Java, and Microsoft had a
fight
– Java is not installed by default in Windows
XP
• How to fix?
– send them to http://java.com for a free
download
Question
What type of sort produces the passes below
(insertion, selection, or bubble)?
10
10
10
2
-37
-37
97
45
45
10
2
2
45
97
63
45
10
10
63
63
97
63
45
45
2
2
2
97
63
63
-37
-37
-37
-37
97
84
84
84
84
84
84
97
ORIGINAL
Pass 1
Pass 2
Pass 3
Pass 4
Pass 5
COMP 14 Today
•
•
•
•
Program 6
HTML
GUIs
Applets
Program 6
•
•
•
•
•
Final Assignment!
100 points
Due: Monday, April 25 at 11:59pm
Builds on Program 5
Add dealer to the game, decide winner, tally
total wins, losses, and ties
• Includes: applet version of Blackjack game,
report written in HTML
Blackjack Dealer Rules
• The dealer is dealt two cards initially
• The dealer's 2nd card is dealt face-down
– known total is only for the face-up card
• Player plays hand to completion
– ending with stand or bust
• Dealer plays hand to completion
– ending with stand or bust
– while point total for hand is < 17, dealer must hit
– once point total for hand is >= 17, dealer must
stand
Blackjack Winner Rules
• Hand closest to 21 without going over bust
wins
• If player busts, dealer wins
– dealer doesn't play hand if player busts
• If dealer busts, player wins
• If dealer and player have same point total, it's
a tie
BlackjackGame
New Class Constants/Variables
• Constants
– 3 integers DEALER, PLAYER, TIE
• Class Variables
– 1 variable to represent the dealer's hand
– 3 integers to keep track of wins, losses, and ties
• class variable - member variable defined as
static, which means there is only one
instance of the variable per class
BlackjackGame
New Methods
•
•
•
•
•
getDealerHand
getWins
getLosses
getTies
addDealerCards
– adds cards to the dealer's hand until the dealer
must stand
– dealer can't have more than
MAX_CARDS_IN_HAND cards
• decideWinner
– return integer (PLAYER, DEALER, or TIE
constant) indicating who won
BlackjackGame
Additions To Existing Methods
• initGame
– instantiate dealer's hand
– initialize number of wins, losses, and ties
• setupNewHand
– make sure deck can deal out 2 full hands
without needing to be shuffled
– reset the dealer's hand
– deal 2 cards to the dealer
Program 6
• Applet
– worth 10 points
– create an applet version of your Blackjack game
(using BlackjackApplet.java)
– put the applet online and include the URL in your
Blackboard comments
Something to Think About:
Would your program still work if we changed only the
value of MAX_CARDS_IN_HAND? (The user interface
will.)
Program 6 Report
• Worth 25 points
• Write a report in HTML (using Notepad -- no
web authoring tools allowed)
• Describe the Card, Hand, and Deck classes
and how they work together
• Describe the algorithm for scoring the hand
• Questions, comments, things learned in
Programs 4-6
• Put report online and include the URL in your
Blackboard comments
Writing Web Pages
• Web pages are written in a "markup"
language called HTML (HyperText Markup
Language)
• HTML is NOT a programming language.
• HTML just tells the computer how to format
text and images--it's like using Word, but
having to type in what you want things to look
like.
Tags
• HTML works based on the concept of tags. A
tag is some text surrounded by < and >
• Tags are not printed to the screen
• Example tags:
– <HTML>, <TITLE>, <P>, <H1>
• A lot of the time they work in pairs:
– <HTML> and </HTML>
• HTML is not case-sensitive
– <HTML> and <html> are the same thing
Very Simple Web Page
<HTML>
<HEAD>
<TITLE>Simple web page</TITLE>
</HEAD>
<BODY>
This is the text on a web page.
</BODY>
</HTML>
simple.html
View any web page source by
choosing Source from the View
menu in a web browser
What Do The Tags Mean?
• <HTML>, </HTML>
– go at the beginning and end of EVERY page
• <HEAD>, </HEAD>
– introduction of the document
• <TITLE>, </TITLE>
– what goes in the title bar of the window
• <BODY>,</BODY>
– the text (and other stuff) that is displayed in the
window
Color and Images
• You can add color or an image to the
background:
– color: make body tag
<BODY BGCOLOR=RED>
OR
<BODY BGCOLOR="#FE23AF">
– image: make body tag
<BODY BACKGROUND="image.gif">
What's #FE23AF?
• RGB color specification
• FE23AF is hexadecimal
– each digit represents 4 binary digits (0-15)
– A=10, B=11, C=12, D=13, E=14, F=15
F
E
2
3
A
F
1111 1110 0010 0011 1010 1111
254
35
175
Ignores White Space
• In HTML, where you put a line break is
ignored. The web browser decides this
for you based on the size of the window
• These two will print the same thing:
first:
<BODY>
Why not fly?
</BODY>
second:
<BODY>
Why
not
fly?
</BODY>
Adding White Space
• Putting <P> at the beginning of a
paragraph and </P> at the end will put
a blank line between two pieces of text
• You can also use <BR> to insert a
carriage return (aka <enter>)
• <hr> will insert a horizontal line
Other Tags
• Bold
– <B> and</B>
• Italic
– <I> and </I>
• Center
– <CENTER> and </CENTER>
• Comments
– <!-- and -->
otherTags.html
Hierarchical Structure
• For documents having a hierarchical
structure, you can use heading tags
– <H1> marking chapter in a book
– <H2> marking section of a chapter
– <H3> marking subsection of a chapter
– <H4> and so on down...
– <H5>
Lists
• There are two kinds of lists:
– Ordered lists (surrounded by <OL> and
</OL>
– Unordered lists (surrounded by <UL> and
</UL>
• Both use <LI> and </LI> to indicate
List Items (things in the list)
Tables
• You can also create tables
• Beginning: <TABLE> </TABLE>
– options: border, cellspacing,
cellpadding
• Each row: <TR> </TR>
• Each column: <TD> </TD>
Links
• This is the important part. This is how
you go from page to page.
• <A HREF="put URL here">text to be
displayed</A>
Inserting Images
• You can also just add an image into the
middle of the page
• Use <IMG SRC="put URL here">
What To Learn More?
• Tutorials
http://www.htmlcodetutorial.com/
http://www.w3.org/MarkUp/Guide/
• Quick Reference
http://werbach.com/barebones/barebones.html
GUIs
• We used JOptionPane to
create a GUI Calculator
using dialog boxes.
• We can create more
complex GUIs using
Java.
Program 6 User Interface
JFrame
content pane
ImageIcon
JLabel
JButton
Before We Get Started...
• JFrame is a class provided by the package
javax.swing
• Instead of instantiating an object of the JFrame
class, we're going to extend the JFrame class
(called inheritance).
• The new class "inherits" features (including
methods and variables) from the existing class -big time-saver!
• We can use all of the methods and variables from
JFrame, while adding our own.
Extending JFrame
• Use the modifier extends, which is a
reserved word
public class BlackjackUITest extends JFrame
{
}
• JFrame is the superclass
• BlackjackUITest is the subclass
Next Step
• We'll need a constructor for BlackjackUITest
– set the window title setTitle
– set the window size setSize
– set the default operation when the close button is
pressed setDefaultCloseOperation
– display the window setVisible(true)
• We'll need a main method
– create an object of the BlackjackUITest class (which
will call the constructor)
import javax.swing.*; // needed for JFrame
public class BlackjackUITest1 extends JFrame
{
private final static String TITLE = "Blackjack";
private final static int WIDTH = 700;
private final static int HEIGHT = 600;
public BlackjackUITest1() // constructor
{
setTitle(TITLE);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
BlackjackUITest1 gui = new BlackjackUITest1();
}
}
Adding Things
• Access the content pane so we can add
things (buttons, labels, images)
Container content = getContentPane();
– Container class is provided by the
java.awt package
– add import statement for java.awt
• Then, we set the layout type and add
things to the content pane
Layout Managers
• FlowLayout
– default
– components are added left to right, top to bottom
• BorderLayout
– consists of NORTH, SOUTH, EAST, WEST, CENTER
regions
– size of CENTER region depends on the number of
components in the EAST and WEST regions
• GridLayout
– define number of rows and columns to get equally sized
cells
– cells are filled left to right, top to bottom
BorderLayout
• Main layout for BlackjackUI is
BorderLayout
content.setLayout(new BorderLayout());
• When adding components with
BorderLayout, you have to specify the
section (using NORTH, SOUTH,
EAST, WEST, CENTER constants from
BorderLayout class)
content.add(item, BorderLayout.SECTION);
JLabels
• We'll identify the regions of the
BorderLayout with labels (text areas)
• JLabel is a region of text
– can be assigned an alignment (leftjustified, right-justified, centered)
JLabel northLabel = new JLabel ("NORTH",
SwingConstants.CENTER);
JLabel southLabel = new JLabel ("SOUTH");
• Text can be changed with setText
method
northLabel.setText ("Changed Text");
Container content = getContentPane();
content.setLayout (new BorderLayout());
JLabel northLabel = new JLabel ("NORTH",
SwingConstants.RIGHT);
content.add (northLabel, BorderLayout.NORTH);
JLabel southLabel = new JLabel ("SOUTH");
content.add (southLabel, BorderLayout.SOUTH);
JLabel westLabel = new JLabel ("WEST",
SwingConstants.CENTER);
content.add (westLabel, BorderLayout.WEST);
JLabel eastLabel = new JLabel ("EAST",
SwingConstants.CENTER);
content.add (eastLabel, BorderLayout.EAST);
JLabel centerLabel = new JLabel ("CENTER",
SwingConstants.CENTER);
content.add (centerLabel, BorderLayout.CENTER);
BlackjackUITest2.java
Colors
• Set the background color of the content pane
• Set the foreground color of the text (JLabels)
• Use Color class from the java.awt package
• Available colors pg. 734
– constants (but lowercase)
• Methods
– darker() - darkens the color
– brighter() - brightens the color
content.setBackground(Color.green.darker().darker());
sets the content pane extra dark green
Color Change Code
// change the colors
content.setBackground(Color.green.darker().darker());
northLabel.setForeground(Color.yellow);
southLabel.setForeground(Color.red.brighter());
westLabel.setForeground(Color.cyan);
eastLabel.setForeground(Color.white);
centerLabel.setForeground(Color.orange);
BlackjackUITest3.java
Adding Images
• We can create images and associate them
with labels
• ImageIcon
– use JPG or GIF images
filename
ImageIcon cardImage = new ImageIcon ("img/0.gif");
• Use setIcon method from JLabel class
centerLabel.setIcon (cardImage);
Text Position Relative to Icon
label.setVerticalTextPosition(vposition);
label.setHorizontalTextPosition(hposition);
SwingConstants.TOP
SwingConstants.CENTER
SwingConstants.BOTTOM
SwingConstants.LEFT
SwingConstants.CENTER
SwingConstants.RIGHT
Icon
QuickTime™ and a
TIFF (Uncompressed) decompressor
are needed to see this picture.
Adding Card Image
// face-down card
ImageIcon cardImage = new ImageIcon("img/0.gif");
centerLabel.setIcon(cardImage);
centerLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
centerLabel.setHorizontalTextPosition(SwingConstants.LEFT);
BlackjackUITest4.java
Adding Buttons
• To create a button, we use the JButton
class
JButton cmdDeal = new JButton ("Deal");
• Add button to the content pane
content.add(cmdDeal);
• Change text of the button with the setText
method
cmdDeal.setText("Hit");
• Enable/disable the button with setEnabled
method
cmdDeal.setEnabled(false);
Buttons and Events
• Button presses trigger action events
• Setup a listener for the event
– actionPerformed method from
ActionListener class
– ActionListener class from the
java.awt.event package
• something else to import
ActionListener
• Special type of class, called interface
• Interface - class that contains only the
method headings and a semicolon
public interface ActionListener
{
public void actionPerformed (ActionEvent e);
}
ActionListener
• We can't instantiate an object of
ActionListener because there's no
implementation
• Specify that our class will implement the
method actionPerformed
public class BlackjackUITest extends JFrame
implements ActionListener
• Implement actionPerformed method in our
class
• Specify this class will listen for action
cmdDeal.addActionListener(this);
Add Buttons
// buttons
cmdDeal = new JButton ("Deal");
cmdDeal.addActionListener(this);
content.add(cmdDeal, BorderLayout.SOUTH);
buttonState = IS_DEAL; // state of button
cmdNewCard = new JButton ("New Card");
cmdNewCard.addActionListener(this);
content.add(cmdNewCard, BorderLayout.NORTH);
When Deal button is pressed, change text to Hit.
When Hit button is pressed, change text to Deal.
When NewCard button is pressed, display a different card
in the center region (centerLabel).
actionPerformed
• Anything we want to access inside the
actionPerformed method, we need
to declare as member variables
– not local to constructor
• Make cmdDeal, cmdNewCard,
centerLabel member variables
instead of local variables
public void actionPerformed (ActionEvent e)
{
if (e.getSource() == cmdDeal) {
// deal/hit button pressed
if (buttonState == IS_DEAL) {
// change text to "Hit"
cmdDeal.setText("Hit");
buttonState = IS_HIT;
}
else {
// change text to "Deal"
cmdDeal.setText("Deal");
buttonState = IS_DEAL;
}
}
continued on next slide
else if (e.getSource() == cmdNewCard) {
// new card button pressed
// pick a
int img =
// make a
ImageIcon
random card (0-52)
(int) (Math.random() * 53);
temporary ImageIcon
temp = new ImageIcon ("img/" + img
+ ".gif");
// set the member variable to the temp ImageIcon
cardImage = temp;
// associate the new ImageIcon with the label
centerLabel.setIcon(cardImage);
}
} // end of actionPerformed method
BlackjackUITest5.java
More Layout
• When we added buttons to SOUTH and
NORTH regions, it overwrote the text
• How to have more than one element in each
region? Nest layouts using panels
• Use JPanel to create sub-frame where we
can place buttons, images, etc.
BorderLayout
NORTH
dealerCardPanel
playerCardPanel
bottomPanel
CENTER
SOUTH
dealerCardPanel
JLabel with
ImageIcon
JPanel dealerCardPanel = new JPanel
(new GridLayout (1, 5));
playerCardPanel
JPanel playerCardPanel = new JPanel
(new GridLayout (1, 5));
JLabel with
ImageIcon
bottomPanel
JPanel bottomPanel = new JPanel
(new GridLayout (3, 1));
JPanel buttonPanel = new JPanel
(new GridLayout (1, 3));
tally (wins, losses, ties)
instructions
Deal/Hit
Stand
Quit
JLabel with
ImageIcon
JLabel with
ImageIcon
tally (wins, losses, ties)
instructions
Deal/Hit
Stand
Quit
BlackjackUI Operation
• Array of 54 ImageIcons
– one for each card (indices 1-52)
– one blank (index 0)
– one face-down (index 53)
• Array of MAX_CARDS_IN_HAND JLabels,
each associated with an ImageIcon for the
player's hand and the dealer's hand
– score displayed in label index 0
• setCard - finds the index of the specified
card (using getFace and getSuit) and picks
the correct image to display
actionPerformed
• Calls various methods based on what
button was pressed
• dealButtonPressed
• standButtonPressed
• hitButtonPressed
Applets
• A Java application is a stand-alone
program with a main method
• A Java applet is a Java program that is
intended to transported over the web
and executed using a web browser
– an applet doesn't have a main method
– needs an extra import statement:
import java.applet.Applet;
Applets
• An applet is embedded into an HTML file
using a tag that references the bytecode file
(ClassName.class) of the applet class
• It is actually the bytecode version of the
program that is transported across the web
• The applet is executed by a Java interpreter
that is part of the browser
– this Java interpreter not included in Windows XP,
must download from java.com
Applet Methods
• Several methods from Applet class that are
invoked automatically at certain points in an
applet's life
– init - executed only once when the applet is
initially loaded
– start - called when applet becomes active (when
browser loads / returns to the page)
– stop - called when applet becomes inactive
(when browser leaves the page)
– paint - automatically executed and is used to
draw the applets contents
Applets and the Web
• Basic HTML file for an applet:
<html> <body>
<applet code = "ClassName.class">
</applet> </body> </html>
• Can also specify size of applet window
<applet code="ClassName.class"
height=200 width=300> </applet>
• Put the applet HTML file (named
something.html) and your Java applet
bytecode (named ClassName.class) in your
public_html folder in AFS space.
Converting Apps to Applet
• See Ch 13, pgs. 745-748
• Extends JApplet instead of JFrame
• No main method
• No constructor
– put code from constructor in init method
• No setVisible, setTitle, or
setSize methods
Want to Learn More?
• Creating a GUI with Swing
http://java.sun.com/docs/books/tutorial/uiswing/
• Creating Applets
http://java.sun.com/docs/books/tutorial/applet/
• Bored this summer?
– convert your GUI Calculator to a GUI using Swing
that looks more like a real calculator (look at
JTextField and JTextArea)