loading...

CS506 Web Design and Development Assignment 3 Solution Fall 2012

Question: 

You have   to develop a GUI base animation application, which moves a ball in a window   in the following pattern given in demo.gif file. Window should not be   resizable. 

Hints:

Use the   concept of inner class for the class which will create graphic image (ball).

Similar   example is already given in handouts. First understand handouts example then   this exercise will be very easy for you.

 Solution:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Animation{
JFrame f;
Timer t;
MyPanel p;
int x, y;
Color color = Color.BLUE;
Graphics2D g2;
JLabel coard;
//Constructor
public Animation(){
 f = new JFrame();
f.setTitle("CS506 Assignment 3");
Container c = f.getContentPane();
c.setLayout(new BorderLayout());
x = 5;
y = 3;
p = new MyPanel();
c.add(p, BorderLayout.CENTER);
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t = new Timer(50, new Handler());
t.start();
}//end Construction
//Main Method
public static void main(String[] args){
 Animation anim = new Animation();
}
//Handler class
class Handler implements ActionListener{
 public void actionPerformed(ActionEvent ev){
 if(f.getWidth()-50 < p.mX){
 x = -5;
p.setBorder(BorderFactory.createLineBorder(g2.getColor(),10));
color = Color.RED;
 }
 if(f.getHeight()-70 < p.mY){
 y = -3;
p.setBorder(BorderFactory.createLineBorder(g2.getColor(),10));
color = Color.GREEN;
 }
if(p.mX < 10){
 x = 5;
p.setBorder(BorderFactory.createLineBorder(g2.getColor(),10));
color = Color.YELLOW;
 }
if(p.mY < 10){
 y = 3;
p.setBorder(BorderFactory.createLineBorder(g2.getColor(),10));
color = Color.CYAN;
 }
 p.mX += x;
p.mY +=y;
coard.setText("X: " + p.mX + " Y: " + p.mY);
p.repaint();
}
}
//end Handler class
//MyPanel class
class MyPanel extends JPanel{
int mX = 100;
int mY = 100;
public MyPanel(){
 coard = new JLabel("X: " + mX + " Y: " + mY);
add(coard);
}
 public void paintComponent(Graphics g){
 super.paintComponent(g);
g2 = (Graphics2D)g;
g2.setColor(color);
g2.fillOval(mX, mY, 20, 20);
 }
}
//end MyPanel class
}
DOWNLOAD SOLUTION HERE
loading...