Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Advanced Computing Workshop Java Programming Java Programming Workshop Table of Contents Java Programming Workshop ................................................................................................................................ 1 Teacher Notes ......................................................................................................................................................... 2 How To ................................................................................................................................................................... 3 Install Java .......................................................................................................................................................... 3 Compiling and running a program ..................................................................................................................... 5 Package a JAR file.............................................................................................................................................. 7 Stage 1: Simple Games ........................................................................................................................................... 8 Top Getting Started Tips .................................................................................................................................... 8 Simple Images .................................................................................................................................................... 9 Tron .................................................................................................................................................................. 10 Physics .............................................................................................................................................................. 13 Race .................................................................................................................................................................. 15 Fly the Copter ................................................................................................................................................... 16 Joust .................................................................................................................................................................. 17 Pong .................................................................................................................................................................. 18 Stage 2: Intermediate Tech ................................................................................................................................... 19 Stars with Arrays .............................................................................................................................................. 20 Gravity .............................................................................................................................................................. 23 Introduction to Post Office Server .................................................................................................................... 24 Objects .............................................................................................................................................................. 25 Stage 3: Advanced Game Techniques .................................................................................................................. 26 Other Projects ....................................................................................................................................................... 27 Network Chat System ....................................................................................................................................... 28 Notes ..................................................................................................................................................................... 32 Allan Callaghan (http://calaldees.dreamhosters.com/) Page 1 of 32 Advanced Computing Workshop Java Programming Teacher Notes This document is free to use and distribute under Creative Commons http://creativecommons.org/licenses/by-nc/2.0/uk/ Java is not the best starting language and I want to convert these resources to use Python and PyGame Future Multiball - objects Platform Post office server and RPG redered Allan Callaghan (http://calaldees.dreamhosters.com/) Page 2 of 32 Advanced Computing Workshop Java Programming How To Install Java Windows 1.) Download & Install the JDK http://java.sun.com/javase/downloads/ Download JDK (Java Development Kit) Run Installer 2.) Setup Path Environment Variable Find jdk/bin folder (example shown below) Copy the complete “bin” path “C:\Program Files\Java\jdk1.6.????\bin” Right click on “My Computer” Advanced/Environment Variables Allan Callaghan (http://calaldees.dreamhosters.com/) Page 3 of 32 Advanced Computing Workshop Java Programming Add “;(your jdk bin location)” to the end of the Path variable NOTE: You must put the ; in Ubuntu Linux 1. 2. 3. 4. Load Synaptic Package Manager Refresh list Search for “jdk” Mark and Install Sun JDK 6 or higher or OpenJDK 6 or higher Allan Callaghan (http://calaldees.dreamhosters.com/) Page 4 of 32 Advanced Computing Workshop Java Programming Compiling and running a program Windows XP Ubuntu Linux GEdit Use the commands Use the commands LS Create program in text editor and save it in your Java Code folder Load a Command Prompt Locate the folder with your java code Allan Callaghan (http://calaldees.dreamhosters.com/) Page 5 of 32 Advanced Computing Workshop DIR CD (folder name) CD .. Compile and Run Use the Commands javac *.java java (filename) [if this is the first time you are running this you will need to compile the GameLib librarys by typing compile_gamelib.bat] Tips Java Programming CD (folder name) CD .. Use the Commands javac *.java java (filename) [if this is the first time … in linux you may need to make the file executable by typing 2 commands: chmod 755 copile_gamelib.bat ./compile_gamelib.bat ] Use TAB to auto complete Filenames and Folder names Use the UP and DOWN arrows to quickly get previous commands Notepad as editor Allan Callaghan (http://calaldees.dreamhosters.com/) Page 6 of 32 Advanced Computing Workshop Java Programming Package a JAR file Allan Callaghan (http://calaldees.dreamhosters.com/) Page 7 of 32 Advanced Computing Workshop Java Programming Stage 1: Simple Games Programming Techniques Command Line (ls,dir,cd) Compilation Integer Double Subroutines IF String Concatenation Game Techniques Colour Comparison Title Screen Physics Scrolling Background Top Getting Started Tips case sensitive { paired with } Indentation Debug a program: System.out.println(“message”+variable) // comments Allan Callaghan (http://calaldees.dreamhosters.com/) Page 8 of 32 Advanced Computing Workshop Java Programming Simple Images Putting an image on the screen import GameLib.GameFrame; public class ????? extends GameFrame { public void mousePressed(int x, int y) { putImage(x,y,"ship.gif"); repaintScreen(); } public static void main(String[] args) {new ????();} } public class ????? extends GameFrame { public void mouseDragged(int x, int y) { putImage(x,y,"ship.gif"); repaintScreen(); } public static void main(String[] args) {new ????();} } This leaves a trail of images. We want to drag our space ship around without this trail public void mouseDragged(int x, int y) { clearScreen(); putImage(x,y,"ship.gif"); repaintScreen(); } Challenge Using these commands can you place stationary shapes on the screen that the drag able ship can be in front the ship and some behind the ship? Replace the x,y,width,height,size with numbers. import GameLib.GameFrame; import java.awt.Color; public class ????? extends GameFrame { public void mouseDragged(int x, int y) { clearScreen(); drawRectangle(50,50,100,50,Color.YELLOW); putImage(x,y,"ship.gif"); drawCircleFilled(200,100,size,Color.RED); drawString(150,200,“This is AWESOME!”); … Add more rectangles and ovals Allan Callaghan (http://calaldees.dreamhosters.com/) Page 9 of 32 Advanced Computing Workshop Java Programming Tron Part 1: Simple Line A Line that Moves import GameLib.GameFrame; import java.awt.Color; import java.awt.event.KeyEvent; public class ??? extends GameFrame { int int int int player1_x_pos = 50; player1_y_pos = 50; player1_x_move = 1; player1_y_move = 0; public void timerEvent() { player1_x_pos = player1_x_pos + player1_x_move; player1_y_pos = player1_y_pos + player1_y_move; putPixel(player1_x_pos,player1_y_pos,Color.YELLOW); repaintScreen(); } public static void main(String[] args) {new ???();} } Keyboard Input Replace the ? with 0, 1 or -1 public void timerEvent() { if (isKeyPressed(KeyEvent.VK_LEFT )) if (isKeyPressed(KeyEvent.VK_RIGHT)) if (isKeyPressed(KeyEvent.VK_UP )) if (isKeyPressed(KeyEvent.VK_DOWN )) {player1_x_move=?; {player1_x_move=?; {player1_x_move=?; {player1_x_move=?; player1_y_move=?;} player1_y_move=?;} player1_y_move=?;} player1_y_move=?;} Player 2 Can you add a second player? if if if if (isKeyPressed(KeyEvent.VK_A (isKeyPressed(KeyEvent.VK_D (isKeyPressed(KeyEvent.VK_W (isKeyPressed(KeyEvent.VK_S )) )) )) )) {???} {???} {???} {???} Part 2: Collisions Get the pixel of where we are about to move to. If it is not black then we have hit an object so reset the players coordinate … public void reset() { clearScreen(); player1_x_pos = 50; player1_y_pos = 50; player1_x_move = 1; player1_y_move = 0; } public static void main(String[] args) {new ???();} Allan Callaghan (http://calaldees.dreamhosters.com/) Page 10 of 32 Advanced Computing Workshop Java Programming if (Color.BLACK.equals(getPixel(player1_x_pos,player1_y_pos))) { putPixel(player1_x_pos,player1_y_pos,Color.YELLOW); } else { reset(); } Part 3: Extras Score int player1_deaths = 0; … else { msgBox("Player1 has crashed: " + player1_deaths); player1_deaths = player1_deaths + 1; reset(); } Background Obstacles … public ???() { reset(); } public void timerEvent() { … public void reset() { clearScreen(); putImage(0,0,”TronLevel.png”); player1_x_pos = 50; player1_y_pos = 50; Part 4: Challenge Ideas Wrap around When you go off one side of the screen you appear the other side. if (player1_x_pos>=getWidth()-1) {player1_x_pos = 1; } if (player1_x_pos<=1 ) {player1_x_pos = getWidth()-2;} 3 players Add new keys (try I,J,K,L) Boost Pressing a button will make your line move twice as fast if (isKeyPressed(KeyEvent.VK_DOWN )) {player1_x_move=0; player1_y_move=1;} if (isKeyPressed(KeyEvent.VK_SPACE)) { player1_x_move = player1_x_move*2; player1_y_move = player1_y_move*2; } To limit people using this all the time, give them a limited about of booster fuel. int player1_boost_fuel = 100; … if (isKeyPressed(KeyEvent.VK_SPACE)) { if (player1_boost_fuel>0) { player1_boost_fuel = player1_boost_fuel – 1; player1_x_move = player1_x_move*2; player1_y_move = player1_y_move*2; } Allan Callaghan (http://calaldees.dreamhosters.com/) Page 11 of 32 Advanced Computing Workshop Java Programming } … public void reset() { player1_boost_fuel = 100; Maze levels Maze is a one player game to get to the red exit. Create a set of level graphics 320 by 240 with a black background. Maze1.png Maze2.png int current_level = 1; … if (Color.BLACK.equals(getPixel(player1_x_pos,player1_y_pos))) { putPixel(player1_x_pos,player1_y_pos,Color.YELLOW); } else if (Color.RED.equals(getPixel(player1_x_pos,player1_y_pos))) { current_level = current_level + 1; reset(); } else { reset(); } … public void reset() { clearScreen(); putImage(0,0,”Maze” + current_level + “.png”); Allan Callaghan (http://calaldees.dreamhosters.com/) Page 12 of 32 Advanced Computing Workshop Java Programming Physics Part 1: Simple Moving Spaceship Before we Begin Install Java Copy needed “GameFrame” files Know how to compile & run java files (“ls”, “dir”, “cd ???”,“javac *.java”, “java ????”) Drawing and Moving a Spaceship import GameLib.GameFrame; import java.awt.event.KeyEvent; public class ????? extends GameFrame { private int ship_x_pos = 60; private int ship_y_pos = 45; public void timerEvent() { if (isKeyPressed(KeyEvent.VK_UP )) if (isKeyPressed(KeyEvent.VK_DOWN )) if (isKeyPressed(KeyEvent.VK_LEFT )) if (isKeyPressed(KeyEvent.VK_RIGHT)) {ship_y_pos {ship_y_pos {ship_x_pos {ship_x_pos +=-1;} += 1;} +=-1;} += 1;} clearScreen(); putImage(ship_x_pos, ship_y_pos,"ship.gif"); repaintScreen(); } public static void main(String[] args) {new ????();} } The spaceship moved in a very jerky and robotic way. We want some physics to make the ship glide. Part 2: Slide and Glide Double Arithmetic Integer store whole numbers (1,69,-7) we need to store double precision numbers (like 3.1415) private double ship_x_pos = 60.5763; private double ship_y_pos = 45; We can only put images at whole number co-ordinates (like [60,45]). Putting an image at [60.5763,45] will not work. putImage((int)ship_x_pos, (int)ship_y_pos,"ship.gif"); We convert the double precision numbers to integers (whole numbers) when we draw the spaceship. You won’t notice much difference when you run it now, but doubles allow us to do cool stuff. Keeping track of current speed private private private private double double double double ship_x_pos = ship_y_pos = ship_x_speed ship_y_speed 60.5763; 45; = 0; = 0; … public void timerEvent() { if (isKeyPressed(KeyEvent.VK_UP )) {ship_y_speed +=-0.1;} if (isKeyPressed(KeyEvent.VK_DOWN )) {ship_y_speed += 0.1;} Allan Callaghan (http://calaldees.dreamhosters.com/) Page 13 of 32 Advanced Computing Workshop Java Programming if (isKeyPressed(KeyEvent.VK_LEFT )) {ship_x_speed +=-0.1;} if (isKeyPressed(KeyEvent.VK_RIGHT)) {ship_x_speed += 0.1;} clearScreen(); ship_x_pos = ship_x_pos + ship_x_speed; ship_y_pos = ship_y_pos + ship_y_speed; putImage((int)ship_x_pos, (int)ship_y_pos,"ship.gif"); repaintScreen(); } Drag Factor The spaceship just keeps moving, we want it to slow down on it’s own public void timerEvent() { … clearScreen(); ship_x_speed = ship_x_speed – (ship_x_speed * 0.01); ship_y_speed = ship_y_speed – (ship_y_speed * 0.01); ship_x_pos = ship_x_pos + ship_x_speed; ship_y_pos = ship_y_pos + ship_y_speed; Constants We are typing the same numbers again and again like (-0.1). Professional programmers create a constant they can change in one place public class ????? extends GameFrame { private final double move_speed = 0.10; private final double drag_factor = 0.01; … ship_x_speed = ship_x_speed – (ship_x_speed * drag_factor); ship_y_speed = ship_y_speed – (ship_y_speed * drag_factor); … if (isKeyPressed(KeyEvent.VK_UP )) {ship_y_speed +=-move_speed;} if (isKeyPressed(KeyEvent.VK_DOWN )) {ship_y_speed += move_speed;} if (isKeyPressed(KeyEvent.VK_LEFT )) {ship_x_speed +=-move_speed;} if (isKeyPressed(KeyEvent.VK_RIGHT)) {ship_x_speed += move_speed;} Part 3: Gravity & Obstacles Gravity If an object is falling under gravity it’s y speed will slowly increase. … ship_y_speed = ship_y_speed – (ship_y_speed * 0.01); ship_y_speed = ship_y_speed + 0.01; ship_x_pos = ship_x_pos + ship_x_speed; … Bouncing Boundaries … ship_y_speed = ship_y_speed + 0.01; if (ship_y_pos > getHeight()) {ship_y_speed = -ship_y_speed;} ship_x_pos = ship_x_pos + ship_x_speed; … Allan Callaghan (http://calaldees.dreamhosters.com/) Page 14 of 32 Advanced Computing Workshop Java Programming Race This task relies on completing Physics and Tron examples. Part 1: Track Create a track image and each timerEvent draw it as a background. The graphic should be 320 by 240 in size (example right) public void timerEvent() { putImage(0,0,"Track1.png"); //keyboard input will go here //code to move car will go here //code to draw car graphics go here repaintScreen(); } Use your physics example to create a graphic that has coordinates and a speed. Part 2: Slow Down on Grass if (Color.BLACK.equals(getPixel(player1_x_pos,player1_y_pos))) { //do nothing because we are on the track } else { //we are off the track //if we are going to fast make our max speed very slow if (player1_xspeed> 0.05) {player1_xspeed=0.05;} if (player1_yspeed> 0.05) {player1_yspeed=0.05;} if (player1_xspeed<-0.05) {player1_xspeed=-0.05;} if (player1_yspeed<-0.05) {player1_yspeed=-0.05;} } Challenge Create 2 players. Allan Callaghan (http://calaldees.dreamhosters.com/) Page 15 of 32 Advanced Computing Workshop Java Programming Fly the Copter Create a new image 2000 by 240 with one colour as the background. Create a cave to fly in like the example and save it as PNG Part 1: Scrolling background import GameLib.GameFrame; public class ????? extends GameFrame { int background_x_pos = 0; public void timerEvent() { background_x_pos = background_x_pos – 1; if (background_x_pos < -2000) {background_x_pos = 0;} putImage(background_x_pos,0,"CopterLevel1.png"); repaintScreen(); } public static void main(String[] args) {new ????();} } Part 2: Moving Copter Simple: Use the physics example. Make the copter move up and down when you press buttons. (try and use double arithmetic for gravity) Part 3: Collision detection Color player_color = getPixel(player1_x_pos,player1_y_pos)); if (Color.BLACK.equals(player_color)) { } else if (Color.YELLOW.equals(player_color)) { current_level = current_level + 1; reset(); else { reset(); } Allan Callaghan (http://calaldees.dreamhosters.com/) Page 16 of 32 Advanced Computing Workshop Java Programming Joust Part 1: Title Screen public Joust() { titleScreen(); } public void keyPressed(int key_event) { if (key_event==KeyEvent.VK_F1 ) {reset();} if (key_event==KeyEvent.VK_EQUALS) {gravity_factor += 0.002; titleScreen();} if (key_event==KeyEvent.VK_MINUS ) {gravity_factor +=-0.002; titleScreen();} } … public void titleScreen() { timerPause(true); clearScreen(); putImage(0,0,"JoustTitle.png"); drawString(100,100,"Player 1: "+player1_score); drawString(100,120,"Player 2: "+player2_score); drawString(100,140,"Gravity: " +gravity_factor); repaintScreen(); } … public void startGame() { //reset player co-ordinates timerPause(false); } Part 2: Collision Detection Highest wins Allan Callaghan (http://calaldees.dreamhosters.com/) Page 17 of 32 Advanced Computing Workshop Java Programming Pong import GameLib.GameFrame; import java.awt.Color; import java.awt.Rectangle; public class Pong extends GameFrame { private private private private Rectangle player1_bat = new Rectangle(20,100,10,40); Rectangle ball = new Rectangle(100,100,5,5); int ball_x_speed = 2; int ball_y_speed = 2; public void timerEvent() { clearScreen(); if (ball.y<0 || ball.y>getHeight()) {ball_y_speed=-ball_y_speed;} if (ball.x>getWidth()) {ball_x_speed=-ball_x_speed;} if (player1_bat.contains(ball.x,ball.y)) {ball_x_speed=-ball_x_speed;} if (ball.x<0) { msgBox("Missed"); ball.x = 200; //ball.y = 200; } ball.x = ball.x + ball_x_speed; ball.y = ball.y + ball_y_speed; drawRectangle(ball, Color.WHITE); drawRectangle(player1_bat,Color.WHITE); repaintScreen(); } public void mouseMoved(int x, int y) { player1_bat.x=x; player1_bat.y=y; } public static void main(String[] args) {new Pong();} } Allan Callaghan (http://calaldees.dreamhosters.com/) Page 18 of 32 Advanced Computing Workshop Java Programming Stage 2: Intermediate Tech Programming Techniques Arrays Loops Collections o Vector o Linked List Objects Multiple Class Files Game Techniques Tools Syntax highlighting Notepad++ Notepad 2 Allan Callaghan (http://calaldees.dreamhosters.com/) Page 19 of 32 Advanced Computing Workshop Java Programming Stars with Arrays One Star import GameLib.GameFrame; import java.awt.Color; public class ??? extends GameFrame { int star_x = 0; int star_y = 100; public void timerEvent() { clearScreen(); star_x = star_x + 1; if (star_x > getWidth()) { star_x = 0; } putPixel(star_x, star_y, Color.WHITE); repaintScreen(); } public static void main(String[] args) {new ???();} } Random Star import java.awt.Color; import java.util.Random; public class ??? extends GameFrame { int star_x = 0; int star_y = 100; private Random random_generator = new Random(); public void timerEvent() { … if (star_x > getWidth()) { star_x = 0; star_y = random_generator.nextInt(getHeight()); } … Two Stars Modify the program above to have another star. The thought of typing that all out for 100 stars does not sound fun. We need a way of storing lots of stars. Allan Callaghan (http://calaldees.dreamhosters.com/) Page 20 of 32 Advanced Computing Workshop Java Programming Part 2: Many Many Stars Star Object We need to create an object called a star. We need to say what a star has. public class ??? extends GameFrame { private SimpleStar my_star = new SimpleStar(); private Random random_generator = new Random(); public void timerEvent() { clearScreen(); my_star.x = my_star.x + 1; if (my_star.x > getWidth()) { my_star.x = 0; my_star.y = random_generator.nextInt(getHeight()); } putPixel(my_star.x, my_star.y, Color.WHITE); repaintScreen(); } public static void main(String[] args) {new ???();} } class SimpleStar { public int x; public int y; } Three Stars public class ??? extends GameFrame { private SimpleStar[] stars = new SimpleStar[3]; private Random random_generator = new Random(); public ???() stars[0] = stars[1] = stars[2] = } { new SimpleStar(); new SimpleStar(); new SimpleStar(); public void timerEvent() { clearScreen(); for (SimpleStar star : stars) { star.x = star.x + 1; if (star.x > getWidth()) { star.x = 0; star.y = random_generator.nextInt(getHeight()); } putPixel(star.x, star.y, Color.WHITE); } repaintScreen(); } public static void main(String[] args) {new ???();} } Allan Callaghan (http://calaldees.dreamhosters.com/) Page 21 of 32 Advanced Computing Workshop Java Programming Many Many Stars private SimpleStar[] stars = new SimpleStar[40]; … public ???() { for (int star_number=0 ; star_number<stars.length ; star_number++) { stars[star_number] = new SimpleStar(); } } This isn’t stars!? This is just a line! Why? Random Start Positions public ???() { for (int star_number=0 ; star_number<stars.length ; star_number++) { SimpleStar s = new SimpleStar(); s.x = random_generator.nextInt(getWidth()); s.y = random_generator.nextInt(getHeight()); stars[star_number] = s; } } Some Stars are faster than others … s.y = r.nextInt(getHeight()); s.speed = random_generator.nextInt(number_of_layers) + 1; stars[star_number] = s; … for (SimpleStar star : stars) { star.x = star.x + star.speed; … class SimpleStar { public int x; public int y; public int speed; } Challenge Can you put a spaceship with spaceship physics on top of the stars? Allan Callaghan (http://calaldees.dreamhosters.com/) Page 22 of 32 Advanced Computing Workshop Java Programming Gravity Allan Callaghan (http://calaldees.dreamhosters.com/) Page 23 of 32 Advanced Computing Workshop Java Programming Introduction to Post Office Server Allan Callaghan (http://calaldees.dreamhosters.com/) Page 24 of 32 Advanced Computing Workshop Java Programming Objects Agents that get extended Agents have images and an act method (greenfoot inspiration) Allan Callaghan (http://calaldees.dreamhosters.com/) Page 25 of 32 Advanced Computing Workshop Java Programming Stage 3: Advanced Game Techniques Post office server example Chat using post office RPG Stage Render stage + moving character Development enviroments Netbeans Allan Callaghan (http://calaldees.dreamhosters.com/) Page 26 of 32 Advanced Computing Workshop Java Programming Other Projects Network Chat Calculator Network AI response Allan Callaghan (http://calaldees.dreamhosters.com/) Page 27 of 32 Advanced Computing Workshop Java Programming Network Chat System Part 1: Setup and Simple Messages Before we Begin Install Java Copy needed “Network Connection” files Know how to compile java files Connecting to a server Create a new .java file based on the code below import GameLib.Net.AbstractNetworkConnection; public class ????? extends AbstractNetworkConnection { public ?????() { networkConnect("?network address?"); } public static void main(String[] args) {new ????();} } Note: ???? must be the name of the file (CASE SENSETIVE) e.g if your file is called “ChatClient.java” ????? would be “ChatClient” Run this code and try to connect to someone’s server. You should see on the servers screen a message that you connected. (To find your IP address type “ifconfig” in Linux or “ipconfig” in Windows) (To run a server type “java GameLib/GameServer show_messages”) Press Ctrl-C to exit Sending A “hello” message to the server public class ?????? extends AbstractNetworkConnection { public ?????() { networkConnect("?network address?"); networkSend("Hello everyone! Mr.T has connected"); } public static void main(String[] args) {new ????();} } Adding this line will send a message when you first connect. BUT! We haven’t written code to SEE messages …. Receiving messages and displaying them public void networkReceive(Object message) { System.out.println(message.toString()); } public static void main(String[] args) {new ????();} THINK! Where would you put this code? Look at the indentation. NOW! With your friends try connecting and disconnecting and try to see each others connect message. Allan Callaghan (http://calaldees.dreamhosters.com/) Page 28 of 32 Advanced Computing Workshop Java Programming Part 2: Creating a GUI to type in Creating a TextField Box We need a GUI (Graphical User Interface) to type messages into. We need to IMPORT Java objects to make our interface import java.awt.*; import java.awt.event.*; import javax.swing.*; Put this code at the very beginning of your file Before you networkConnect setup a Java Frame (JFrame) and Java TextField (JTextField) private JTextField text_field; public ?????() { JFrame frame = new JFrame("Martins Mega Chat Client"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); text_field = new JTextField(); frame.add(text_field,BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); networkConnect("?network address?"); networkSend("Hello everyone! Mr.T has connected"); } You should see a box pop up! Good work! But it doesn’t work. Why? Creating a Listener for our JTextField public class ChatClient extends AbstractNetworkConnection implements ActionListener { … text_field = new JTextField(); text_field.addActionListener(this); frame.add(text_field,BorderLayout.SOUTH); … public void actionPerformed(ActionEvent event) { networkSend(text_field.getText()); } Use the code to make the JTextField send a message when you press enter. BUT! What is wrong? (It doesn’t work like we want, why?) Resetting the JTextField Can you fix the bug but using the Java API (Application Programming Interface) Google for “Java API” Find the documentation for JTextField Find the command to use, remember you want to “set the text in the box to nothing” public void actionPerformed(ActionEvent event) { networkSend( text_field.getText() ); text_field.set????(""); } Allan Callaghan (http://calaldees.dreamhosters.com/) Page 29 of 32 Advanced Computing Workshop Java Programming Part 3: Creating a GUI to view received messages Creating a JTextArea box private JTextField text_field; private JTextArea text_area; public ?????() { JFrame frame = new JFrame("Martins Mega Chat Client"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); text_field = new JTextField(); frame.add(text_field,BorderLayout.SOUTH); text_area = new JTextArea(); frame.add(text_area,BorderLayout.CENTER); frame.pack(); … Run it and resize your chat window and check your JTextArea is there (it will be plain white) Receiving messages to the JTextArea public void networkReceive(Object message) { text_area.append(message.toString() + "\n"); } Check your program receives messages BUT! What is wrong? (It doesn’t work like we want, why?) Scrolling the JTextArea … text_area = new JTextArea(); JScrollPane scroll = new JScrollPane(text_area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); frame.add(scroll,BorderLayout.CENTER); frame.pack(); … Final Bugs There are a few more bugs to squash (use the “reference”/”useful code” section below) 1. We can type over the received messages area 2. We want lines to wrap to the next line if they are too long 3. When a message is received we always want it scrolled to the bottom Look at the next Reference section. Can you fix the bugs? Challenges See the reference section below + teacher for hints 1. Extreme Challenge: can you get it to connect to servers by “java ChatClient 192.168.0.12” 2. Can you make it so it puts your name in front of every message that you type? 3. Ultimate Challenge: can you make it “java ChatClient 192.168.0.12 Ninja” (where Ninja the name it will print before each line) 4. Think: What could be done to improve this system if it was going to be used for real? Allan Callaghan (http://calaldees.dreamhosters.com/) Page 30 of 32 Advanced Computing Workshop Java Programming Reference Useful code text_area.setEditable(false); text_area.setLineWrap(true); text_field.setText(""); text_area.setCaretPosition(text_area.getDocument().getLength()); Network Connection Methods Reference Method networkConnect(String) networkDisconnect() networkSend(Object) networkIsConnected() public void networkRecieve(String message) { public void networkConnected() { public void networkDisconnecting() { Type Description You write it You write it You write it Extreme Challenge Help … public ChatClient(String server_address) { … networkConnect(?); } … public static void main(String[] args) { new ChatClient(args[0]); } … Ultimate Challenge Help private String username; … public ChatClient(String server_address, String new_username) { username = new_username; … networkConnect(?); } … networkSend(username + ": " + text_field.getText()); … public static void main(String[] args) { new ChatClient(args[0],args[1]); } … Allan Callaghan (http://calaldees.dreamhosters.com/) Page 31 of 32 Advanced Computing Workshop Java Programming Notes Add Delay Add Image Size Add Image Scale Add Sound + Music Joystick input ReFactor into Jar? Post office client and examples Allan Callaghan (http://calaldees.dreamhosters.com/) Page 32 of 32