Useful
Java Stuff
Making a grid-based game? Follow the instructions on this page.
Making a simple graphical project that is not based on a grid? Download this starter code.
Making a project with lots of moving sprites, not based on a grid? Start from the Sprite Lab.
(And here are some notes on inheritance.)
Making a project where the user will draw on the screen? Download this starter code.
Want a simple example where the computer will draw on the screen? Download this file.
Using 3-D graphics? Read these instructions.
Making a networking project? Download this starter code.
(Later, you can use this FakeServer.jar to test your client-side code
and this FakeClient.jar to test your server-side code.)
Looking for other useful stuff in Java? Here's what you'll find on this page:
Main method
Random int
Exceptions
Convert between int and String
Test if a String represents an integer
User input
Wait for user to press enter
Load from a text file
Save to a text file
Wait
Time something
Threads
Exit the program
GUI (graphical user interface)
Pop-Up Dialogs
Custom Dialogs
Drawing
Draw Text
Draw an image
Rotate an image
Animation
Gravity: jumping and falling
Mouse Input
Keyboard Input
Smooth movement with keyboard input
Sound
Networking: Client
Networking: Server
Main method
public static void main(String[] args)
{
}
Random int
int n = (int)(Math.random() * howManyPossibleValues) + lowestPossibleValue;
Exceptions
There are 2 kinds of exceptions in Java: run-time and compile-time. Run-time exceptions occur when a program crashes. For example,
int n = 3 / 0;
Program compiles successfully, but crashes with an ArithmeticException
You can use the throw instruction to force your program to crash. (Forcing your program to crash immediately in the event of an error condition is much better than ignoring the error condition and allowing the program to continue running.) This code will compile successfully, but will crash at run-time.
if (numTimes < 0)
throw new RuntimeException("cannot be negative");
You can prevent your code from crashing by detecting when an exception occurs.
try
{
doStuff();
System.out.println("It worked!");
}
catch(SomeKindOfException e)
{
System.out.println("It failed.");
}
Compile-time exceptions (such as IOException) must be handled by your program or your code won't even compile. There are two ways to handle a compile-time exception. One way is to catch it, as shown above. The other is to declare that your method throws the exception.
public static void save() throws IOException
{ ... }
Of course, now whoever calls save will need to handle this exception.
Convert between int and String
String s = 3 + "";
int n = Integer.parseInt("3");
Test if a String represents an integer
try
{
int n = Integer.parseInt(s);
System.out.println("integer");
}
catch(NumberFormatException e)
{
System.out.println("not an integer");
}
User input
import java.util.*; //for Scanner
...
Scanner in = new Scanner(System.in); //only once per program
System.out.print("Enter first name: ");
String first = in.nextLine();
System.out.print("Enter last name: ");
String last = in.nextLine();
Wait for user to press enter
new java.util.Scanner(System.in).nextLine();
Load from a text file
import java.io.*; //for BufferedReader, FileReader
...
BufferedReader in = new BufferedReader(new FileReader("file.txt"));
String line = in.readLine();
while (line != null)
{
System.out.println(line);
line = in.readLine();
}
in.close();
Save to a text file
import java.io.*; //for PrintWriter, FileWriter
...
PrintWriter out = new PrintWriter(new FileWriter("file.txt"), true);
out.println("first line");
out.println("second line");
out.close();
Wait
//before waiting
try { Thread.sleep(500); } catch(Exception e) { }
//half a second later
Time something
long start = System.currentTimeMillis();
...
long millisecondsElapsed = System.currentTimeMillis() - start;
Threads
This class extends Thread and overrides its run method to print forever.
public class MyThread extends Thread
{
public void run()
{
while (true)
System.out.println("running");
}
}
The following code creates the thread and runs it, and then prints at the same time.
Thread t = new MyThread();
t.start();
while (true)
System.out.println("at the same time");
Consider the following code segment, which appears in some method.
a();
b();
c();
Here's a quick and dirty way to rewrite this code so that methods b and c run at the same time:
a();
new Thread()
{
public void run()
{
b();
}
}.start();
c();
Exit the program
System.exit(0);
GUI (graphical user interface, pronounced "gooey")
import java.awt.event.*; //for ActionListener, ActionEvent
import javax.swing.*; //for JFrame, BoxLayout, JLabel, JTextField, JButton
public class GUI implements ActionListener
{
private JTextField field;
public GUI()
{
//make a window
JFrame frame = new JFrame();
frame.setTitle("My Window");
//tell window to place each new component under the previous ones
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
//add some text
frame.getContentPane().add(new JLabel("some text"));
//add a text field
field = new JTextField(25);
frame.getContentPane().add(field);
//add a button
JButton button = new JButton("a button");
frame.getContentPane().add(button);
//tell button to call this object's actionPerformed method when pressed
button.addActionListener(this);
//store text in button that can be retrieved in actionPerformed method
button.setActionCommand("button1");
frame.pack(); //determine best size for window
frame.setVisible(true); //show the window
}
public void actionPerformed(ActionEvent e)
{
//button was pressed
if (e.getActionCommand().equals("button1"))
{
//we now know which button was pressed
System.out.println("text field contains: " + field.getText());
}
}
}
Pop-Up Dialogs
You will need:
import javax.swing.*; //for JOptionPane
Dialog with OK button:
JOptionPane.showMessageDialog(parentComponent, "Hard drive erased");
Dialog with text field:
String name = JOptionPane.showInputDialog(parentComponent, "Enter your name");
Dialog with Yes/No/OK/Cancel buttons:
int selected = JOptionPane.showConfirmDialog(parentComponent,
"Are you sure?", "Confirm", JOptionPane.YES_NO_OPTION);
if (selected == JOptionPane.YES_OPTION)
...
Dialog with drop-down:
Object[] choices = {"blue", "green", "red", "yellow"};
Object selected = JOptionPane.showInputDialog(parentComponent, "What is your favorite color?",
"Color", JOptionPane.PLAIN_MESSAGE, null, choices, choices[0]);
Custom Dialogs
Here is a complete example of a custom dialog.
public class SimpleDialog extends JDialog implements ActionListener
{
private JTextField field;
public SimpleDialog(Frame frame)
{
super(frame, true);
field = new JTextField(25);
field.addActionListener(this);
getContentPane().add(field);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
setVisible(false);
}
public String getResult()
{
return field.getText();
}
}
This following code segment shows how to use the custom dialog.
SimpleDialog dialog = new SimpleDialog(frame);
String result = dialog.getResult();
Drawing
import java.awt.*; //for Graphics
import javax.swing.*; //for JComponent, JFrame
public class Draw extends JComponent
{
public Draw()
{
JFrame frame = new JFrame();
setPreferredSize(new Dimension(400, 400));
frame.getContentPane().add(this);
frame.pack();
frame.setVisible(true);
}
public void paintComponent(Graphics g)
{
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.RED);
g.drawOval(100, 100, 200, 200);
}
}
Draw Text
In the paintComponent method:
g.setColor(Color.BLUE); // optional code to choose color before drawing text
g.setFont(new Font(null, Font.PLAIN, 24)); // optional code to change the font size
g.drawString("Hello", 10, 200); // places the bottom-left of the string at position (10, 200).
Draw an image
You will need:
import java.awt.*; //for Image
import java.net.*; //for URL
import javax.swing.*; //for ImageIcon
Create a fields for storing images:
private Image image; //need to import java.awt.*;
Load images:
String fileName = "somefile.png";
URL url = getClass().getResource(fileName);
if (url == null)
throw new RuntimeException("file not found: " + fileName);
image = new ImageIcon(url).getImage();
In paintComponent method:
g.drawImage(image, x, y, null);
Rotate an Image
Graphics2D g2 = (Graphics2D)g; //g is a Graphics object
AffineTransform old = g2.getTransform();
g2.rotate(angleInRadians, centerX, centerY); //rotate around center of image at (centerX, centerY)
g2.drawImage(image, leftX, topY, null); //(leftX, topY) is top left of image (before rotating)
g2.setTransform(old);
Animation (automatic graphical changes not triggered by user input)
Create a class that extends JComponent. Store state in fields:
private int x;
In paintComponent method, what you draw should depend on state:
g.fillOval(x, 100, 10, 10);
Write a loop to change state and redraw:
while (true)
{
x++; //change state
repaint(); //tell JComponent to redraw when it has time
try { Thread.sleep(100); } catch(Exception e) { } //provide time to redraw
}
Gravity: jumping and falling
Declare fields to keep track of both position and velocity:
private double y;
private double vely;
Repeatedly change position and velocity, and redraw:
while (true)
{
y = y + vely; //change y coordinate by amount of velocity
vely = vely + 0.01; //change velocity by constant acceleration due to gravity
repaint();
try { Thread.sleep(10); } catch(Exception e) { }
}
To begin falling, set velocity to 0. To begin jumping, set velocity to a negative value:
vely = -10;
Mouse input
You will need:
import java.awt.event.*; //for MouseListener, MouseEvent
Create a class that extends JComponent and implements MouseListener. In the constructor, tell the component to notify itself of mouse events:
addMouseListener(this);
Implement each of the methods in MouseListener, such as:
public void mousePressed(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
System.out.println("Pressed mouse button at: " + x + ", " + y);
}
Keyboard input
You will need:
import java.awt.event.*; //for KeyListener, KeyEvent
Create a class that extends JComponent and implements KeyListener. In the constructor, tell the component to notify itself of keyboard events:
setFocusable(true);
addKeyListener(this);
Implement each of the methods in KeyListener, such as:
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
System.out.println("Pressed key with code: " + key);
}
Smooth movement with keyboard input
Create a field to remember whether a key is down, and initialize it to false.
private boolean rightKeyDown;
Set the field to true when the key is pressed and false when the key is released.
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == 39) //right arrow key
rightKeyDown = true;
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if (key == 39) //right arrow key
rightKeyDown = false;
}
Repeatedly change coordinate values when the field is true.
while (true)
{
if (rightKeyDown)
x++;
repaint();
try { Thread.sleep(10); } catch(Exception e) { }
}
New Way to Play Sound
There are multiple ways to play sound in Java. Here is the newer way.
import java.io.*;
import javax.sound.sampled.*;
...
//load sound
Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));
clip.open(AudioSystem.getAudioInputStream(new File("beep.wav")));
...
//play sound
clip.setFramePosition(0);
clip.start();
This code throws 3 compile-time exceptions: LineUnavailableException, IOException, UnsupportedAudioFileException.
Old Way to Play Sound in Java
Java originally only supported AIFF, AU, and WAV files. These must use 8- or 16-bit sample rates from 8 kHz to 48 kHz. If you use an unsupported file, the sound will not play, but no error will occur. You can use Audacity to convert sounds to the correct format. Specifically, Audacity has a drop down on the left side of each sound that lets you change the sample rate, and then you can export the sound as WAV.
import java.applet.*; //for Applet
import java.net.*; //for URL
...
private AudioClip beepSound; //instance variable
...
//probably in a constructor
String fileName = "beep.wav";
URL url = getClass().getResource(fileName);
if (url == null)
throw new RuntimeException("cannot find file: " + fileName);
beepSound = Applet.newAudioClip(url);
...
//to play the sound
beepSound.play();
Networking: Client
import java.io.*; //for BufferedReader, InputStreamReader, PrintWriter
import java.net.*; //for Socket
...
Socket socket = new Socket("localhost", 9000); //connect to server on port 9000
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("lowercase"); //send message to server
String line = in.readLine(); //wait for message from server
System.out.println(line); //print message from server
...
//disconnect from server
in.close();
out.close();
socket.close();
Networking: Server
import java.io.*; //for BufferedReader, InputStreamReader, PrintWriter
import java.net.*; //for ServerSocket, Socket
...
ServerSocket server = new ServerSocket(9000); //start server on port 9000
while (true)
{
Socket socket = server.accept(); //wait for client to connect
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String line = in.readLine(); //wait for message from client
out.println(line.toUpperCase()); //send message to client
//disconnect from client
in.close();
out.close();
socket.close();
}