Saucymeatman
Saucymeatman

Reputation: 617

How do I draw an image to a frame every second?

This is all I have so far. I have read the oracle documentation on drawing and creating images, But I still cant figure it out.

        final BufferedImage image = ImageIO.read(new File("BeachRoad_double_size.png"));

    final JPanel pane = new JPanel();

    frame.add(pane);


    int delay = 1000; //milliseconds
    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            Graphics gg = image.getGraphics();
            System.out.println("sdfs");
            pane.paintComponents(gg);
            //g.drawImage(image, 0, 0, null);
        }
    };
    new Timer(delay, taskPerformer).start();

Upvotes: 0

Views: 1042

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

  1. Painting is the responsibility to of the Swing framework. It decides what, when and how much should be painted. You can make requests to the system to perform updates, but it will be up to the sub system to decide when it will be executed.
  2. You should never have a need to call paintComponent directly, in fact, you should never have a need to call paint directly
  3. Your example is actually painting the component to the image.

Instead. Create a custom component, say from something like JPanel, override it's paintComponent method and perform all you custom painting there...

public class ImagePane extends JPanel {
    private BufferedImage bg;

    public ImagePane(BufferedImage bg) {
        this.bg = bg;
    }

    public Dimension getPreferredSize() {
        return bg = null ? new Dimension(200, 200) : new Dimension(bg.getWidth(), bg.getHeight());
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (bg != null) {
            g.drawImage(bg, 0, 0, this);
        }
    }
}

Take a look at

For more details

Upvotes: 3

Related Questions