Zielony Smok - logo witryny

Timery

Odmierzaniem czasu zajmują się trzy klasy:

  • java.util.Timer
  • java.util.TimerTask
  • javax.swing.Timer

Nie będziemy tych klas szczegółowo omawiać, ale pokażemy przykłady ich użycia. Tę samą animację wykonamy przy użyciu klasy wątku Thread, klas java.util.Timer i java.util.TimerTask oraz klasy javax.swing.Timer.

Klasa Listing094 pozwala na kolejne uruchomienie 3 klasy: Listing094a, Listing094b i Listing094c. Mamy również 3 klasy pomocnicze: Card i CardUtil oraz FileJPGFilter.

Użycie klasy Thread

Klasa Listing094a
package dt16.timers;
import java.awt.*;
import java.io.*;
import javax.swing.*;
/**
 * animacja z uzyciem klasy Thread CardLayout
 */
class Listing094a extends JPanel {
    private static final long serialVersionUID = -1708095494186169452L;
    private final CardLayout cl;
    private final File[] files;
    private int frames;
    public Listing094a() {
        cl = new CardLayout();
        setPreferredSize(new Dimension(182, 335));
        setBounds(0, 0, 182, 335);
        setLayout(cl);
        files = CardUtil.listJPGFiles("assets/karty/");
        frames = files.length;
        for (File file : files) {
            Card card = new Card("" + file);
            add(card, "" + file);
        }
        new Thread(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            while (frames > 0) {
                Listing094a.this.repaint();
                try {
                    cl.next(Listing094a.this);
                    Thread.sleep(170);
                    frames--;
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }).start();
    }
}

Użycie klasy java.swing.Timer

Listing094b
package dt16.timers;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
/**
 * animacja z wykorzystaniem klasy Timer i CardLayout
 */
class Listing094b extends JPanel implements ActionListener {
    private static final long serialVersionUID = -1708095494186169452L;
    private final CardLayout cl;
    private final File[] files;
    private int frames;
    private final Timer timer;
    public Listing094b() {
        cl = new CardLayout();
        setPreferredSize(new Dimension(182, 335));
        setBounds(0, 0, 182, 335);
        setLayout(cl);
        files = CardUtil.listJPGFiles("assets/karty/");
        frames = files.length;
        for (File file : files) {
            Card card = new Card("" + file);
            add(card, "" + file);
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        timer = new Timer(170, this);
        timer.start();
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (frames > 0) {
            Listing094b.this.repaint();
            cl.next(Listing094b.this);
            frames--;
        } else {
            timer.stop();
        }
    }
}

Użycie klas java.util.Timer i java.util.TimerTask

Klasa Listing094c
package dt16.timers;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.Timer;
import javax.swing.*;
/**
 * animacja z uzyciek klasy Timer i TimerTask i CardLayout
 */
class Listing094c extends JPanel {
    private static final long serialVersionUID = -1708095494186169452L;
    private final CardLayout cl;
    private final File[] files;
    private int frames;
    private final TimerTask timerTask;
    private final Timer timer;
    public Listing094c() {
        cl = new CardLayout();
        setPreferredSize(new Dimension(182, 335));
        setBounds(0, 0, 182, 335);
        setLayout(cl);
        files = CardUtil.listJPGFiles("assets/karty/");
        frames = files.length;
        for (File file : files) {
            Card card = new Card("" + file);
            add(card, "" + file);
        }
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (frames > 0) {
                    Listing094c.this.repaint();
                    cl.next(Listing094c.this);
                    frames--;
                } else {
                    timer.cancel();
                }
            }
        };
        timer.schedule(timerTask, 500, 170);
    }
}

Klasy pomocnicze

Klasa Listing094
package dt16.timers;
import java.awt.*;
import javax.swing.*;
/**
 * ramka + panel
 */
class Listing094 extends JFrame {
    private static final long serialVersionUID = 1L;
    private final int frameWidth = 800;
    private final int frameHeight = 800;
    private final JPanel panel;
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Listing094(new Listing094c()));
    }
    private Listing094(JComponent comp) {
        panel = (JPanel) comp;
        setLayout(null);
        //panel.setBounds(0, 0, 182, 335);
        panel.setBounds(0, 0, 800, 800);
        setPreferredSize(new Dimension(800, 800));
        setBounds(
                (Toolkit.getDefaultToolkit().getScreenSize().width / 2)
                        - (frameWidth / 2),
                (Toolkit.getDefaultToolkit().getScreenSize().height / 2)
                        - (frameHeight / 2),
                frameWidth, frameHeight);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Card Layout");
        //    setResizable(false);
        add(panel);
        setVisible(true);
    }
}
Klasa Card
package dt16.timers;
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class Card extends JComponent {
    private static final long serialVersionUID = 5586338595500806338L;
    private static final int XSIZE = 182;
    private static final int YSIZE = 335;
    private final BufferedImage bimage;
    public Card(String obrazek) {
        bimage = CardUtil.fileToBimage3(obrazek);
        setLayout(null);
        setBounds(0, 0, XSIZE, YSIZE);
        setPreferredSize(new Dimension(XSIZE, YSIZE));
    }
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(bimage, 0, 0, XSIZE, YSIZE, this);
    }
}
Klasa CardUtil
package dt16.timers;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
class CardUtil {
    private CardUtil() {
    }
    public static File[] listJPGFiles(String dir) {
        File file = new File(dir);
        File[] files = null;
        if (file.isDirectory()) {
            FileJPGFilter fef = new FileJPGFilter(file, ".jpg");
            files = file.listFiles(fef);
        } else {
            System.out.println("Podaj nazwę katalogu z obrazkami");
        }
        return files;
    }
    public static BufferedImage fileToBimage3(String plik) {
        Image obrazek = loadImage(plik);
        BufferedImage bimage;
        GraphicsConfiguration gc = GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration();
        bimage = gc.createCompatibleImage(obrazek.getWidth(null),
                obrazek.getHeight(null));
        bimage.getGraphics().drawImage(obrazek, 0, 0, null);
        return bimage;
    }
    private static Image loadImage(String obrazek) {
        Image image = Toolkit.getDefaultToolkit().getImage(obrazek);
        MediaTracker mt = new MediaTracker(new JPanel());
        mt.addImage(image, 0);
        try {
            mt.waitForID(0);
        } catch (InterruptedException e) {
            e.getMessage();
        }
        return image;
    }
}
Klasa FileJPGFilter
package dt16.timers;
import java.io.*;
//tworzy filtr rozszerzen plikow, ktore beda wyszukiwane przy jego uzyciu
class FileJPGFilter implements FilenameFilter {
    public FileJPGFilter(File dir, String s) {
        this.accept(dir, s);
    }
    @Override
    public boolean accept(File dir, String s) {
        return s.endsWith(".jpg") || s.endsWith(".jpeg") || s.endsWith(".JPG");
    }
}

Wynik

Po uruchomieniu zobaczymy kolejne karty:

Animacja kart
Animacja kart

Rysunki kart: Maciej Krzywicki.