Download presentation
Presentation is loading. Please wait.
1
COMP 14 Introduction to Programming
Michele Weigle - COMP 14 - Spring 2004 COMP 14 Introduction to Programming Mr. Joshua Stough April 6, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218
2
Michele Weigle - COMP 14 - Spring 2004
Announcements Program 6 assigned today
3
Michele Weigle - COMP 14 - Spring 2004
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 Remote host: isis.unc.edu Remote username: your Onyen These directions are also in the instructions for Program 6
4
Michele Weigle - COMP 14 - Spring 2004
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 for a free download
5
Michele Weigle - COMP 14 - Spring 2004
Question What type of sort produces the passes below (insertion, selection, or bubble)? ORIGINAL Pass 1 Pass 2 Pass 3 Pass 4 Pass 5
6
Michele Weigle - COMP 14 - Spring 2004
COMP 14 Today Program 6 HTML GUIs Applets
7
Michele Weigle - COMP 14 - Spring 2004
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 Demo applet
8
Blackjack Dealer Rules
Michele Weigle - COMP 14 - Spring 2004 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 while point total for hand is < 17, dealer must hit once point total for hand is >= 17, dealer must stand
9
Blackjack Winner Rules
Michele Weigle - COMP 14 - Spring 2004 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
10
BlackjackGame New Class Constants/Variables
Michele Weigle - COMP 14 - Spring 2004 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
11
BlackjackGame New Methods
Michele Weigle - COMP 14 - Spring 2004 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
12
BlackjackGame Additions To Existing Methods
Michele Weigle - COMP 14 - Spring 2004 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
13
Michele Weigle - COMP 14 - Spring 2004
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.)
14
Michele Weigle - COMP 14 - Spring 2004
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
15
Michele Weigle - COMP 14 - Spring 2004
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.
16
Michele Weigle - COMP 14 - Spring 2004
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
17
Michele Weigle - COMP 14 - Spring 2004
Very Simple Web Page <HTML> <HEAD> <TITLE>Simple web page</TITLE> </HEAD> <BODY> This is the text on a web page. </BODY> </HTML> View any web page source by choosing Source from the View menu in a web browser simple.html
18
Michele Weigle - COMP 14 - Spring 2004
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
19
Michele Weigle - COMP 14 - Spring 2004
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">
20
Michele Weigle - COMP 14 - Spring 2004
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 254 35 175
21
Michele Weigle - COMP 14 - Spring 2004
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>
22
Michele Weigle - COMP 14 - Spring 2004
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
23
Michele Weigle - COMP 14 - Spring 2004
Other Tags Bold <B> and</B> Italic <I> and </I> Center <CENTER> and </CENTER> Comments <!-- and --> otherTags.html
24
Hierarchical Structure
Michele Weigle - COMP 14 - Spring 2004 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>
25
Michele Weigle - COMP 14 - Spring 2004
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)
26
Michele Weigle - COMP 14 - Spring 2004
Tables You can also create tables Beginning: <TABLE> </TABLE> options: border, cellspacing, cellpadding Each row: <TR> </TR> Each column: <TD> </TD>
27
Michele Weigle - COMP 14 - Spring 2004
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>
28
Michele Weigle - COMP 14 - Spring 2004
Inserting Images You can also just add an image into the middle of the page Use <IMG SRC="put URL here">
29
Michele Weigle - COMP 14 - Spring 2004
What To Learn More? Tutorials Quick Reference Added to External Links on Blackboard
30
Michele Weigle - COMP 14 - Spring 2004
GUIs We used JOptionPane to create a GUI Calculator using dialog boxes. We can create more complex GUIs using Java.
31
Program 6 User Interface
Michele Weigle - COMP 14 - Spring 2004 Program 6 User Interface JFrame content pane ImageIcon The window itself is called a JFrame. Everything under the title bar is called the content pane. We can add things, such as images, buttons, and text in the content pane. JLabel JButton
32
Michele Weigle - COMP 14 - Spring 2004
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. If you take COMP 114, you'll learn alot more about inheritance
33
Michele Weigle - COMP 14 - Spring 2004
Extending JFrame Use the modifier extends, which is a reserved word JFrame is the superclass BlackjackUITest is the subclass public class BlackjackUITest extends JFrame { }
34
Michele Weigle - COMP 14 - Spring 2004
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)
35
Michele Weigle - COMP 14 - Spring 2004
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(); } } BlackjackUITest1
36
Michele Weigle - COMP 14 - Spring 2004
Adding Things Access the content pane so we can add things (buttons, labels, images) 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 Container content = getContentPane();
37
Michele Weigle - COMP 14 - Spring 2004
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
38
Michele Weigle - COMP 14 - Spring 2004
BorderLayout Main layout for BlackjackUI is BorderLayout When adding components with BorderLayout, you have to specify the section (using NORTH, SOUTH, EAST, WEST, CENTER constants from BorderLayout class) content.setLayout(new BorderLayout()); content.add(item, BorderLayout.SECTION);
39
Michele Weigle - COMP 14 - Spring 2004
JLabels We'll identify the regions of the BorderLayout with labels (text areas) JLabel is a region of text can be assigned an alignment (left-justified, right-justified, centered) Text can be changed with setText method JLabel northLabel = new JLabel ("NORTH", SwingConstants.CENTER); JLabel southLabel = new JLabel ("SOUTH"); northLabel.setText ("Changed Text");
40
Michele Weigle - COMP 14 - Spring 2004
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); Getting access to the content pane Creating a new label that contains the text of the border layout region and adding that label to the region Default alignment is left-justified BlackjackUITest2.java
41
Michele Weigle - COMP 14 - Spring 2004
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
42
Michele Weigle - COMP 14 - Spring 2004
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
43
Michele Weigle - COMP 14 - Spring 2004
Adding Images We can create images and associate them with labels ImageIcon use JPG or GIF images Use setIcon method from JLabel class ImageIcon cardImage = new ImageIcon ("img/0.gif"); filename centerLabel.setIcon (cardImage);
44
Text Position Relative to Icon
Michele Weigle - COMP 14 - Spring 2004 Text Position Relative to Icon label.setVerticalTextPosition(vposition); label.setHorizontalTextPosition(hposition); SwingConstants.TOP SwingConstants.CENTER SwingConstants.BOTTOM SwingConstants.LEFT SwingConstants.CENTER SwingConstants.RIGHT Icon
45
Michele Weigle - COMP 14 - Spring 2004
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
46
Michele Weigle - COMP 14 - Spring 2004
Adding Buttons To create a button, we use the JButton class Add button to the content pane Change text of the button with the setText method Enable/disable the button with setEnabled method JButton cmdDeal = new JButton ("Deal"); content.add(cmdDeal); cmdDeal.setText("Hit"); cmdDeal.setEnabled(false);
47
Michele Weigle - COMP 14 - Spring 2004
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
48
Michele Weigle - COMP 14 - Spring 2004
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); }
49
Michele Weigle - COMP 14 - Spring 2004
ActionListener We can't instantiate an object of ActionListener because there's no implementation Specify that our class will implement the method actionPerformed Implement actionPerformed method in our class Specify this class will listen for action public class BlackjackUITest extends JFrame implements ActionListener cmdDeal.addActionListener(this);
50
Michele Weigle - COMP 14 - Spring 2004
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).
51
Michele Weigle - COMP 14 - Spring 2004
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
52
Michele Weigle - COMP 14 - Spring 2004
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
53
Michele Weigle - COMP 14 - Spring 2004
else if (e.getSource() == cmdNewCard) { // new card button pressed // pick a random card (0-52) int img = (int) (Math.random() * 53); // make a temporary ImageIcon 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
54
Michele Weigle - COMP 14 - Spring 2004
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.
55
Michele Weigle - COMP 14 - Spring 2004
BorderLayout NORTH dealerCardPanel CENTER playerCardPanel SOUTH bottomPanel
56
Michele Weigle - COMP 14 - Spring 2004
dealerCardPanel JLabel with ImageIcon JPanel dealerCardPanel = new JPanel (new GridLayout (1, 5));
57
Michele Weigle - COMP 14 - Spring 2004
playerCardPanel JPanel playerCardPanel = new JPanel (new GridLayout (1, 5)); JLabel with ImageIcon
58
Michele Weigle - COMP 14 - Spring 2004
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
59
Michele Weigle - COMP 14 - Spring 2004
JLabel with ImageIcon JLabel with ImageIcon tally (wins, losses, ties) instructions Deal/Hit Stand Quit
60
Michele Weigle - COMP 14 - Spring 2004
61
BlackjackUI Operation
Michele Weigle - COMP 14 - Spring 2004 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
62
Michele Weigle - COMP 14 - Spring 2004
actionPerformed Calls various methods based on what button was pressed dealButtonPressed standButtonPressed hitButtonPressed
63
Michele Weigle - COMP 14 - Spring 2004
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;
64
Michele Weigle - COMP 14 - Spring 2004
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
65
Michele Weigle - COMP 14 - Spring 2004
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
66
Michele Weigle - COMP 14 - Spring 2004
Applets and the Web Basic HTML file for an applet: Can also specify size of applet window Put the applet HTML file (named something.html) and your Java applet bytecode (named ClassName.class) in your public_html folder in AFS space. <html> <body> <applet code = "ClassName.class"> </applet> </body> </html> <applet code="ClassName.class" height=200 width=300> </applet> The whole idea behind applets was to be able to run a program over the web
67
Converting Apps to Applet
Michele Weigle - COMP 14 - Spring 2004 Converting Apps to Applet See Ch 13, pgs Extends JApplet instead of JFrame No main method No constructor put code from constructor in init method No setVisible, setTitle, or setSize methods
68
Michele Weigle - COMP 14 - Spring 2004
Want to Learn More? Creating a GUI with Swing Creating Applets Bored this summer? convert your GUI Calculator to a GUI using Swing that looks more like a real calculator (look at JTextField and JTextArea) Links are under External Links on Blackboard
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.