在java中跨GUI移动图像

时间:2014-03-12 20:13:10

标签: java swing user-interface timer

所以我必须在GUI上移动我的(多个)图像,但无论出于什么原因,我的paint方法只被调用两次,即使我的x变量和我的计时器,我用来尝试移动图像,正在递增。任何帮助都会得到满足!谢谢

  import javax.swing.*;
import java.awt.*;
import java.lang.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;


public class Races extends JFrame 
{
public int threadCount = 5;
public int x = 0;
public ImageIcon picture = new ImageIcon("races.jpeg");
public int height = picture.getIconHeight();
public int width = picture.getIconHeight();


public Races(int _threadCount)
{
   threadCount = _threadCount;
   int counter = 0;
   while(counter<threadCount)
   {
      (new Thread(new RacesInner(threadCount))).start();
      counter++;
   }
   initialize();
}



  public static void main(String[] args)
   {
     if(args.length == 0)
     {
         JFrame f = new Races(5);
       }
        else
     {
        JFrame f = new Races(Integer.parseInt(args[0]));
    }   
   }


    public void initialize()
   {
     this.setVisible(true);
        this.setTitle("Off to the Races - By ");
      RacesInner inner = new RacesInner(threadCount);
       this.add(inner);
      this.setSize((width*20),(height*3)*threadCount);
       this.setLocationRelativeTo(null);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       this.repaint();
   }   


    protected class RacesInner extends JPanel implements Runnable
    {
        public int j = (int)(Math.random() * 50) + 20;

         public void timer()
          {
          Timer timer1 = new Timer(j, new ActionListener()
          {
             public void actionPerformed(ActionEvent e) 
              {
                   x += 2;
                    repaint();
             }
          });
          timer1.start();
          }


         public void run()
        {
            timer();
         }

       @Override
       public void paint(Graphics g) 
       {
         super.paintComponent(g);
        //drawing the correct amount of icons based on input(or lack of input, default 5)

          //Get the current size of this component
          Dimension d = this.getSize();
         //draw in black
        g.setColor(Color.BLACK);
        //calculating where finish line should be and drawing the line 
        int finishLine;
        finishLine = (width*20)-(width*2);
         g.drawLine(finishLine,0,finishLine,2000);
         for(int i =0; i<threadCount; i++)
        {
         picture.paintIcon(this,g,1+x,(50*i)); 
        }
      }

      public RacesInner(int _threadCount)
      {
         threadCount = _threadCount;
         System.out.println(threadCount);

          //JPanel
         this.setVisible(true);
          this.setLayout(new GridLayout(threadCount,1)); 
      }

   }//closes RacesInner class


 }//closes races class

0 个答案:

没有答案