/* ECE 462 Object-Oriented Programming using C++ and Java by Yung-Hsiang Lu, Purdue University This program is for reference only. It is YOUR RESPONSIBILITY to discover and correct mistakes, if any. If you find a mistake, please inform the instructor. */ import java.awt.Color; import java.awt.Graphics; import java.awt.BorderLayout; import java.util.Random; import javax.swing.JApplet; import javax.swing.JFrame; class Main { public static void main(String[] args) { JFrame jf = new JFrame("Hello Applet"); NewJApplet nja = new NewJApplet(360, 250); jf.getContentPane().add(nja, BorderLayout.CENTER); jf.pack(); jf.setSize(400, 300); jf.setVisible(true); } } class NewJApplet extends JApplet { boolean inApplet = true; int jaWidth = 350; int jaHeight = 200; Color jaBackground = Color.YELLOW; double jaX, jaY; double jaVx, jaVy; int jaSize = 6; public NewJApplet() { inApplet = true; init(); } public NewJApplet(int w, int h) { jaWidth = w; jaHeight = h; inApplet = false; init(); } private void makeUnit() { double magnitude = Math.sqrt(jaVx * jaVx + jaVy * jaVy); if (magnitude > 0) { jaVx /= magnitude; jaVy /= magnitude; } } public void init() { if (inApplet) { jaWidth = getWidth(); jaHeight = getHeight(); jaBackground = Color.LIGHT_GRAY; } else { jaBackground = Color.CYAN; } setSize(jaWidth, jaHeight); Random ranObj = new Random(); jaVx = ranObj.nextDouble() + 0.2; jaVy = ranObj.nextDouble() + 0.2; makeUnit(); jaX = jaWidth / 2; jaY = jaHeight / 2; } public void paint(Graphics gfx) { gfx.setColor(jaBackground); gfx.fillRect(0, 0, jaWidth, jaHeight); gfx.setColor(Color.BLACK); gfx.drawString(String.valueOf(inApplet), jaWidth / 2, jaHeight / 2); jaX += jaVx; jaY += jaVy; if (jaX < jaSize) { jaX = jaSize; jaVx = -jaVx; } if (jaX > (jaWidth - jaSize)) { jaX = (jaWidth - jaSize); jaVx = -jaVx; } if (jaY < jaSize) { jaY = jaSize; jaVy = -jaVy; } if (jaY > (jaHeight - jaSize)) { jaY = (jaHeight - jaSize); jaVy = -jaVy; } gfx.setColor(Color.RED); gfx.fillOval((int) jaX, (int) jaY, jaSize, jaSize); try { Thread.sleep(10); } catch (InterruptedException exp) { } repaint(); } }