Created
March 12, 2013 16:46
-
-
Save figengungor/5144574 to your computer and use it in GitHub Desktop.
Java GUI >> Basic Animation
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 javax.swing.*; | |
| import java.awt.*; | |
| import javax.swing.JPanel; | |
| public class MyGUI | |
| { | |
| public int x=0; | |
| public int y=0; | |
| public static void main(String[] args) | |
| { | |
| MyGUI gui=new MyGUI(); | |
| gui.play(); | |
| } | |
| public void play() | |
| { | |
| JFrame frame=new JFrame(); | |
| frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
| DrawPanel draw=new DrawPanel(x,y); | |
| //frame.getContentPane().add(draw); //same thing, eat nut. | |
| frame.add(draw); | |
| frame.setSize(500,500); | |
| frame.setVisible(true); | |
| for(int i=0;i<250;i++) | |
| { | |
| draw.x++; | |
| draw.y++; | |
| draw.repaint(); //tells the panel to redraw itself so we can see the circle in new location | |
| //If you don't do try-catch thread, you only see the last position of circle on the screen when i=249 | |
| //That for loop run very fast so you can't see the movement | |
| //we'll use thread to slow it by 25 miliseconds each loop, so we can see the movement of the circle | |
| try{ | |
| Thread.sleep(25); | |
| }catch(Exception e) | |
| {} | |
| } | |
| } | |
| } | |
| class DrawPanel extends JPanel{ | |
| int x,y; | |
| public DrawPanel(int x,int y) | |
| { | |
| this.x=x; | |
| this.y=y; | |
| } | |
| public void paintComponent(Graphics g) | |
| { | |
| g.setColor(Color.WHITE);//try to comment out this | |
| g.fillRect(0,0,this.getWidth(),this.getHeight());// and this, it'll be fun! | |
| g.setColor(Color.GREEN); | |
| g.fillOval(x, y, 50,50); | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment