Create a bouncing face in java

Problem:

Create a bouncing face.

Output:



Prompt Picture Description




Solution:

//****************BouncingFaceFrame.java******************/
import javax.swing.JFrame;

public class BouncingFaceFrame {


public static void main(String[] args) {

JFrame frame = new JFrame("Happy Face");

frame.getContentPane().add(new BouncingFacePanel());
frame.pack();
frame.setVisible(true);

}

}
//****************BouncingFacePanel.java******************.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class BouncingFacePanel extends JPanel{


private final int WIDTH = 300, HEIGHT = 300;
private final int DELAY = 20, IMAGE_SIZE = 35;

private ImageIcon icon;
private int x, y, moveX, moveY;
private Timer timer;

public BouncingFacePanel() {
timer = new Timer(DELAY, new ReboundListener());

icon = new ImageIcon("images.jpg");

x = 5; y=40;
moveX = moveY = 3;

setBackground(Color.WHITE);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
timer.start();
timer.addActionListener(new ReboundListener());

}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
icon.paintIcon(this, g, x, y);
}

private class ReboundListener implements ActionListener {

@Override
public void actionPerformed(ActionEvent arg0) {

x += moveX;
y += moveY;

if ( x <= 0 || x >= (WIDTH-IMAGE_SIZE)) moveX *= -1;
if ( y <= 0 || y >= (WIDTH-IMAGE_SIZE)) moveY *= -1;

repaint();
}

}
}


1 comment :

  1. 5D liposuction Korea Korea's #1 Liposculpture Clinic. Lydian plastic surgery is the home of VIP patients. Celebrities, Influencers and Diplomats all know and trust Doctor An and Lydian plastic surgery clinic to provide detailed results.

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact