Created
March 12, 2013 18:02
-
-
Save figengungor/5145290 to your computer and use it in GitHub Desktop.
Java GUI >> Basic Animation 2 (super.paintComponent(), repaint())
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
| /*1. JPanel has an opaque property. | |
| 2. By default it is true. | |
| 3. JPanel's paintComponent method contains the code the draws the background color, when it is opaque. | |
| 4. When you subclass JPanel and override paintComponent, it's up to you to remember to call super.paintComponent; if you don't call the code it wouldn't be called otherwise. | |
| 5. That's it. "Losing opaqueness" should really be thought of as "subclassing and making a mistake. | |
| */ | |
| 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) | |
| { | |
| x+=vel; | |
| y+=vel; | |
| repaint(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment