// Scott DeRuiter 3/12/2003
// FindCircle.java
// Move around a grid until you find a circle.
// 13-feb-27 - Greenstein - Changed from JApplet to JFrame
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FindCircle extends JFrame implements KeyListener, FocusListener,
MouseListener
{
private int hiddenx, hiddeny, userx, usery;
private ThePanel canvas;
private JFrame frame; // 13-feb-27
public FindCircle ( )
{
hiddenx = (int)(Math.random ( ) * 20) + 1;
hiddeny = (int)(Math.random ( ) * 20) + 1;
userx = usery = 1;
}
public static void main(String[] args)
{
FindCircle fc = new FindCircle();
fc.Run();
}
public void Run ( )
{
frame = new JFrame(); // Create the JFrame
// make program quit as soon as you close the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// give the frame a size in pixels
frame.setSize(500, 600);
// Create the drawing JPanel
canvas = new ThePanel();
canvas.setBackground(Color.gray);
// add all the listeners to the panel
canvas.addFocusListener(this);
canvas.addKeyListener(this);
canvas.addMouseListener(this);
// Add the JPanel to the frame
frame.getContentPane().add(canvas);
// Make the JFrame visible
frame.setVisible(true);
}
class ThePanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor ( Color.blue );
for ( int row = 1; row <= 20; row++ )
for ( int col = 1; col <= 20; col++ )
g.fillRect ( 20 * col, 20 * row, 20, 20 );
g.setColor ( Color.red );
g.fillRect ( 20 * userx, 20 * usery, 20, 20 );
if ( userx == hiddenx && usery == hiddeny )
{
g.setColor ( Color.red );
g.drawString ( "YOU FOUND ME!", 20 * hiddenx - 35, 20 * hiddeny - 3 );
g.setColor ( Color.white );
g.fillOval ( 20 * hiddenx + 2, 20 * hiddeny + 2, 16, 16 );
}
}
}
public void focusGained(FocusEvent evt)
{
canvas.repaint();
}
public void focusLost(FocusEvent evt)
{
canvas.repaint();
}
public void mousePressed(MouseEvent evt)
{
canvas.requestFocus();
}
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void keyTyped ( KeyEvent e ) {}
public void keyPressed ( KeyEvent e )
{
int value = e.getKeyCode();
if ( value == KeyEvent.VK_DOWN )
usery++;
else if ( value == KeyEvent.VK_UP )
usery--;
else if ( value == KeyEvent.VK_RIGHT )
userx++;
else if ( value == KeyEvent.VK_LEFT )
userx--;
if ( userx > 20 )
userx = 1;
if ( usery > 20 )
usery = 1;
if ( userx < 1 )
userx = 20;
if ( usery < 1 )
usery = 20;
canvas.repaint ( );
}
public void keyReleased ( KeyEvent e ) {}
}
Back to Lesson 26 Examples
Back to Java Main Page