简体   繁体   中英

How do you use a timer to move images and how do you create a loop for your timer?

I am trying to make a mini game where images move in from all four corners and try to attack you. But I can't seem to make the images start advancing towards the middle. My code usually prints one picture then does nothing after that. I want to make the images move towards the center but I can't figure out how to loop my timer to make that work. I'm not very good at explaining so i'll put all of my code here.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Game extends JPanel  {
private static  int PREF_W = 700;
private static  int PREF_H = PREF_W;
public int count = 0;
private int randCount = (int)(Math.random()*3000 + 10000);
private int randCount1 = (int)(Math.random()*100 + 50);
private int count1,count2,count3 = 0;
boolean x = true;
private static Timer t;

public Game() {
  setFocusable(true);
  requestFocusInWindow();

  addKeyListener(new KeyAdapter() {

     @Override
     public void keyTyped(KeyEvent e) {
        myKeyEvt(e, "keyTyped");
     }

     @Override
     public void keyReleased(KeyEvent e) {
        myKeyEvt(e, "keyReleased");
     }

     @Override
     public void keyPressed(KeyEvent e) {
        myKeyEvt(e, "keyPressed");
     }

     private void myKeyEvt(KeyEvent e, String text) {
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_KP_UP || key == KeyEvent.VK_UP)
        {
            count = 1;

            repaint();
            //Call some function
        }
        if (key == KeyEvent.VK_KP_LEFT || key == KeyEvent.VK_LEFT)
        {
            count =2;

            repaint();
            //Call some function
        }
        if (key == KeyEvent.VK_KP_DOWN || key == KeyEvent.VK_DOWN)
        {
            count = 3;

            repaint();
            //Call some function
        }

        else if (key == KeyEvent.VK_KP_RIGHT || key == KeyEvent.VK_RIGHT)
        {
            count = 4;

            repaint();
            //Call some function
        }

     }

  });

   t = new Timer(randCount, new ActionListener(){

       @Override
       public void actionPerformed(ActionEvent evt){
           if(count1 == 0)
           {
               PREF_H = ((PREF_H/15)+randCount1);
               count2 = 5;
               System.out.print("dasfasfdsadf");
               repaint(count2);
               count1 += 1;
               t = new Timer(randCount1,this);
               if(PREF_H > (PREF_H/2))
               { 
                   t.stop();
               }

           }
           else if(count1 == 1)
           {
               count2 = 10;

               System.out.print("dasfasfdsadf");
               repaint(count2);
               count1 = 2;
               t = new Timer(randCount1,this);
               count1 = 2;
               if(PREF_W > (PREF_W/2))
               { 
                   t.stop();
               }
           }
           else if(count1 == 2)
           {
               count2 = 15;

               System.out.print("dasfasfdsadf");
               repaint(count2);
               count1 = 3;
               t = new Timer(randCount1,this);
               count1 = 3;
               if(PREF_H > (PREF_H/2))
               { 
                   t.stop();
               }
           }
           else if(count1 == 3)
           {
               count2 = 20;

               System.out.print("dasfasfdsadf");
               repaint(count2);
               count1 = 0;
               t = new Timer(randCount1,this);
               count1 = 0;
               if(PREF_W > (PREF_W/2))
               { 
                   t.stop();
               }
           }

       }
   });

      Game.start();      

  }

    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.

public static void start()
{

t.start();
System.out.print("ssssssssssssss");

  }

   public void paintComponent(Graphics g)
             { 
                 Image StartScreenImage =      Toolkit.getDefaultToolkit().getImage("GameField.jpg");
                   g.drawImage(StartScreenImage,0,0,PREF_W,PREF_H,0,0,900,504,this);

                 Color pokemonGreen = new Color(185,235,160);
                 setBackground(pokemonGreen);

                 if(count==3)
                 {
                  Image Player = Toolkit.getDefaultToolkit().getImage("Player.jpg");
                 g.drawImage(Player,(PREF_W/2),(PREF_H/2),((PREF_W/2)+46),((PREF_H/2)+40),0,0,46,40,this);


                 }
                 if(count == 2)
                 {
                     Image Player2 = Toolkit.getDefaultToolkit().getImage("Player2.jpg");
                 g.drawImage(Player2,(PREF_W/2),(PREF_H/2),((PREF_W/2)+46),((PREF_H/2)+40),0,0,46,40,this); 

                 }
                 if(count == 4)
                 {
                     Image Player4 = Toolkit.getDefaultToolkit().getImage("Player4.jpg");
                 g.drawImage(Player4,(PREF_W/2),(PREF_H/2),((PREF_W/2)+46),((PREF_H/2)+40),0,0,46,40,this);    
                 }
                 if(count == 1)
                 {
                     Image Player3 = Toolkit.getDefaultToolkit().getImage("Player3.jpg");
                 g.drawImage(Player3,(PREF_W/2),(PREF_H/2),((PREF_W/2)+46),((PREF_H/2)+40),0,0,46,40,this);    
                 }
                 if(count2 == 5)
                 {
                      Image Zubat = Toolkit.getDefaultToolkit().getImage("Zubat.jpg");
                 g.drawImage(Zubat,((PREF_W/2)-27),(PREF_H),this);
                  System.out.print("11111111");
                  count1 += 1;
                  t.stop();
                  start();
                 }
                 if(count2 == 10)
                 {
                      Image Zubat4 = Toolkit.getDefaultToolkit().getImage("Zubat4.jpg");
                 g.drawImage(Zubat4,((PREF_W/15)+randCount1),((PREF_H/2)),this);
                  System.out.print("22222222222222");
                  count1 += 1;
                  t.stop();
                  start();

                 }
                 if(count2 == 15)
                 {
                      Image Zubat3 = Toolkit.getDefaultToolkit().getImage("Zubat3.jpg");
                 g.drawImage(Zubat3,((PREF_W/2)+randCount1),((PREF_H/15)),this);
                  System.out.print("3333333333333");
                  count1 += 1;
                  t.stop();
                  start();

                 }
                 if(count2 == 20)
                 {
                      Image Zubat2 = Toolkit.getDefaultToolkit().getImage("Zubat2.jpg");
                 g.drawImage(Zubat2,((PREF_W/15)-randCount1),((PREF_H/2)),this);
                  System.out.print("44444444444444");
                  count1=0;
                  t.stop();
                  start();

                 }

             }
     @Override
     public Dimension getPreferredSize() {
  return new Dimension(PREF_W, PREF_H);
      }

    private static void createAndShowGui() {
  Game mainPanel = new Game();

  JFrame frame = new JFrame("Dungeon Of Geometry");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel);
  frame.pack();
  frame.setLocationByPlatform(true);
  frame.setVisible(true);

     }
    public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
     public void run() {
        createAndShowGui();
     }
  });
     }
   }

I believe that this may be something similar to what you want. It creates a JPanel and randomly moves a red dot within the panel overtime the timer sets off a message. My understanding was that your main problem was trying to get the scheduled actions to kick off and I believe that this will do it.

package bradleyross.experiments;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.lang.reflect.InvocationTargetException;
import java.awt.event.KeyEvent;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
 * This Swing demo creates a JPanel component and randomly 
 * moves a red dot within the panel when triggered by a
 * timer.
 * 
 * @author Bradley Ross
 *
 */
public class SwingTimer implements Runnable{
    protected JFrame mainFrame;
    protected FlowLayout layout;
    protected MyPanel panel;
    protected int xPos = 0;
    protected int yPos = 0;
    protected Random random = new Random();
    protected Timer timer = new Timer();
    public void run() {
        buildFrame();
    }
    /**
     * Action listener for this application.
     * @author Bradley Ross
     *
     */
    protected class Listener1 implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            System.out.println("Action " + e.getActionCommand());
        }

    }
    /**
     * Key listener for this application.
     * @author Bradley Ross
     *
     */
    protected class Listener2 implements KeyListener {
        /** 
         * Action when key event is detected.
         *  @param e key event
         */
        public void keyTyped(KeyEvent e) {
            System.out.println("Keystroke received " + e.getKeyChar());
        }
        public void keyPressed(KeyEvent e) { ; }
        public void keyReleased(KeyEvent e) { ; }

    }
    /**
     * This subclass of JPanel repaints the
     * the dot using {@link SwingTimer#xPos} and 
     * {@link SwingTimer#yPos}.
     * 
     * @author Bradley Ross
     *
     */
    @SuppressWarnings("serial")
    public class MyPanel extends JPanel {
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillOval(xPos,  yPos, 5, 5);
        }
    }
    /**
     * Executed each time the timer triggers an event.
     * 
     * <p>It randomly repositions the dot within the
     *    panel.</p>
     * @author Bradley Ross
     *
     */
    public class Motion extends TimerTask {
        public void run() {
            xPos = random.nextInt(300);
            yPos = random.nextInt(300);
            panel.repaint();
        }
    }
    public void buildFrame() {
        xPos = random.nextInt(300);
        yPos = random.nextInt(300);
        KeyListener listener2 = new Listener2();
        ActionListener listener1 = new Listener1();
        mainFrame = new JFrame();
        layout = new FlowLayout(FlowLayout.LEADING);
        mainFrame.setLayout(layout);
        mainFrame.addKeyListener(listener2);
        JButton first = new JButton("First");
        first.setActionCommand("first");
        first.addActionListener(listener1);
        first.addKeyListener(listener2);
        first.setFocusable(false);
        mainFrame.add(first);
        mainFrame.setFocusable(true);
        panel = new MyPanel();
        panel.setBorder(BorderFactory.createLineBorder(Color.black));
        panel.setPreferredSize(new Dimension(300,300));
        panel.setForeground(Color.red);
        panel.addKeyListener(listener2);
        panel.repaint();
        timer.scheduleAtFixedRate(new Motion(), 0  , 2000);
        mainFrame.add(panel);
        mainFrame.setSize(500, 500);
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.setVisible(true);
    }
    /**
     * Main driver.
     * @param args not used in this example
     */
    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new SwingTimer());
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM