Last active
December 14, 2015 20:39
-
-
Save figengungor/5145437 to your computer and use it in GitHub Desktop.
Java GUI >> Basic Animation (bounce back logic added)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.awt.Color; | |
| import java.awt.Graphics; | |
| import java.awt.event.ActionEvent; | |
| import java.awt.event.ActionListener; | |
| import javax.swing.JFrame; | |
| import javax.swing.JPanel; | |
| import javax.swing.Timer; | |
| public class MyGUI extends JPanel implements ActionListener | |
| { | |
| Timer tm = new Timer(5, this); //this refers to ActionListener's event? | |
| int x=0,y=0,vel=1; | |
| public void paintComponent(Graphics g) | |
| { | |
| /*If your paintComponent() method wants to clear the background area all it has | |
| to do is call the super paintComponent() method and make the component opaque when it is initialized.*/ | |
| super.paintComponent(g); | |
| g.setColor(Color.RED); | |
| g.fillRect(x, y, 50, 30); | |
| tm.start(); //this starts ActionEvent after 5 miliseconds | |
| } | |
| public static void main(String[] args) | |
| { | |
| MyGUI gui=new MyGUI(); | |
| JFrame frame = new JFrame(); | |
| frame.setTitle("Basic Animation"); | |
| frame.setSize(500,500); | |
| frame.setVisible(true); | |
| frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
| frame.add(gui); | |
| } | |
| public void actionPerformed(ActionEvent arg0) | |
| { | |
| if(x<0 || x>450) //bounce it back style!!! | |
| vel=-vel; | |
| x+=vel; | |
| y+=vel; | |
| repaint(); | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment