Question: Turn this JApplet into a JFrame: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Whack extends JApplet implements MouseListener, ActionListener { private final int WIDTH
Turn this JApplet into a JFrame:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Whack extends JApplet implements MouseListener, ActionListener {
private final int WIDTH = 300, HEIGHT = 100;
private final int DELAY = 20, IMAGE_SIZE = 35;
private final int N = 10;
private Image image;
private Timer [] timers;
private int[] x, y;
private int[] moveX, moveY;
private int alive;
private JPanel panel;
public void init() {
panel = new JPanel ();
timers = new Timer[N];
x = new int[N];
y = new int[N];
moveX = new int[N];
moveY = new int[N];
image = getImage(getDocumentBase(), "happyFace.png");
alive = N;
for (int i = 0; i < N; i++) {
timers[i] = new Timer(DELAY, this);
x[i] = (int)(Math.random() * (WIDTH - IMAGE_SIZE));
y[i] = (int)(Math.random() * (HEIGHT - IMAGE_SIZE));
moveX[i] = moveY[i] = 3;
}
panel.setPreferredSize (new Dimension(WIDTH, HEIGHT));
panel.setBackground (Color.black);
for (Timer timer : timers)
timer.start();
addMouseListener(this);
add(panel);
} // init
public void paint (Graphics page) {
super.paint (page);
if (alive > 0) {
for (int i = 0; i < N; i++)
if (timers[i].isRunning())
page.drawImage(image, x[i], y[i], this);
}
else {
page.setColor(Color.yellow);
page.drawString("R.I.P.", WIDTH / 2 - 20, HEIGHT / 2 - 5);
}
} // paint
public void actionPerformed (ActionEvent event) {
Timer timer = (Timer)event.getSource();
int i = 0;
while (i < N && timer != timers[i])
i++;
if (timers[i].isRunning()) {
x[i] += moveX[i];
y[i] += moveY[i];
if (x[i] <= 0 || x[i] >= WIDTH - IMAGE_SIZE)
moveX[i] = moveX[i] * -1;
if (y[i] <= 0 || y[i] >= HEIGHT - IMAGE_SIZE)
moveY[i] = moveY[i] * -1;
}
repaint();
} // actionPerformed
public void mousePressed(MouseEvent event) {
int xloc = event.getX();
int yloc = event.getY();
int i = 0;
while (i < N) {
if (timers[i].isRunning() &&
xloc >= x[i] && xloc <= x[i] + IMAGE_SIZE &&
yloc >= y[i] && yloc <= y[i] + IMAGE_SIZE) {
alive--;
timers[i].stop();
repaint();
break;
}
i++;
}
} // mousePressed
public void mouseEntered(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
} // class Whack
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
