Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.SwingUtilities;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.BorderFactory;
- import java.awt.Color;
- import java.awt.Dimension;
- import java.awt.Graphics;
- import java.awt.Image;
- import java.awt.MediaTracker;
- import java.awt.Toolkit;
- public class SwingPaintDemo {
- public static void main(String[] args) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- createAndShowGUI();
- }
- });
- }
- private static void createAndShowGUI() {
- System.out.println("Created GUI on EDT? "+
- SwingUtilities.isEventDispatchThread());
- JFrame f = new JFrame("Swing Paint Demo");
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- f.add(new MyPanel());
- f.pack();
- f.setVisible(true);
- }
- }
- class MyPanel extends JPanel {
- Image [] img;
- MediaTracker tracker;
- int index = 0;
- int maxImg;
- private void loadImages() {
- img = new Image[2]; // 2 images in animation
- tracker = new MediaTracker(this);
- System.out.println("Loading images...");
- maxImg = img.length - 1;
- try {
- // images loading
- img[0] = Toolkit.getDefaultToolkit().getImage("src/ill/frame0.gif");
- img[1] = Toolkit.getDefaultToolkit().getImage("src/ill/frame1.gif");
- tracker.addImage(img[0],0);
- tracker.addImage(img[1],1);
- tracker.waitForAll();
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- AnimationThread at = new AnimationThread();
- at.delayedAnimation(this, 20);
- at.start();
- System.out.println("Started");
- }
- public MyPanel() {
- setBorder(BorderFactory.createLineBorder(Color.black));
- loadImages();
- }
- public Dimension getPreferredSize() {
- return new Dimension(800,800);
- }
- public void paintComponent(Graphics g) {
- super.paintComponent(g);
- // Draw Text
- g.drawString("This is my custom Panel!",10,20);
- if (img[0] != null) {
- g.drawImage(img[index],0,20,this);
- index = (index < maxImg) ? index + 1 : 0;
- }
- }
- public void animate() {
- repaint();
- }
- class AnimationThread extends Thread {
- MyPanel animationApplet;
- int delay;
- public void delayedAnimation(MyPanel a, int delay) {
- this.animationApplet = a;
- this.delay = delay;
- }
- public void run() {
- while (true) {
- try {
- sleep(delay);
- animationApplet.animate();
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement