Hello all
I am trying to make an applet that makes a cube bounce up and down continuously. I made it go all the way down, but don't know how to make it go back up. Here is the code.
/**
* This is the applet class for the Ramblecs game.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ramblecs extends JApplet
implements ActionListener
{
private LetterPanel whiteboard;
private JButton go;
public void init()
{
whiteboard = new LetterPanel();
whiteboard.setBackground(Color.red);
go = new JButton("Go");
go.addActionListener(this);
Container c = getContentPane();
c.add(whiteboard, BorderLayout.CENTER);
c.add(go, BorderLayout.EAST);
}
/**
* Processes Go button events.
*/
public void actionPerformed(ActionEvent e)
{
whiteboard.dropCube();
}
}
/**
* Implements a falling letter cube for the Ramblecs game
*/
import java.awt.*;
public class FallingCube
{
private final int xLeft; // Left margin for cubes
private final int cubeSize;
private int cubeX, cubeY; // Cube coordinates (upper left corner)
private int yStep;
private int nStep;
// Distance (in pixels) to move down
// in one timer cycle
private static final String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private char randomLetter; // Cube letter
public FallingCube(int size)
{
cubeSize = size;
xLeft = cubeSize / 3;
yStep = cubeSize / 17;
cubeX = -cubeSize; // off the board --
cubeY = -cubeSize;
}
public void start()
{
int i = (int)(Math.random() * letters.length());
randomLetter = letters.charAt(i);
cubeX = 0;
cubeY = -cubeSize; // above the board for smooth entry
}
public boolean moveDown()
{
if (cubeY < 11 * cubeSize) // board's height is 7 * cubesize
{
cubeY += yStep;
return true;
}
else
{
nStep += -yStep;
return true;
}
}
public void draw(Graphics g)
{
int x = xLeft + cubeX;
int y = cubeY;
g.setColor(Color.red);
g.fill3DRect(x, y, cubeSize-1, cubeSize-1, true);
g.setColor(Color. white);
g.fillRoundRect(x + 5, y + 5, cubeSize - 10, cubeSize - 10,
cubeSize/2 - 5, cubeSize/2 - 5);
g.setColor(Color.darkGray);
String s = String.valueOf(randomLetter);
g.drawString(s, x + cubeSize/2 - 6, y + cubeSize/2 + 5);
}
}
/**
* Implements a panel on which "letter cubes" fall
* in the Ramblecs applet
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LetterPanel extends JPanel
implements ActionListener
{
private FallingCube cube;
private final int CUBESIZE = 70;
private final int delay = 10;
private Timer t;
public LetterPanel()
{
cube = new FallingCube(CUBESIZE);
t = new Timer(delay, this);
}
public void dropCube()
{
cube.start();
t.start();
}
/**
* Processes timer events
*/
public void actionPerformed(ActionEvent e)
{
boolean moved = cube.moveDown();
if (!moved) // "If not moved... "
{
t.stop();
}
repaint();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g); // call JPanel's paintComponent
cube.draw(g);
}
}
I know I have to create a new variable. This program contains three classes. Any help would greatly be appreciated.
Thanks!