如何移动JFrame形状

时间:2015-06-20 13:34:32

标签: java swing animation awt java-2d

我正在尝试开发一款简单的游戏。游戏是关于形状的。形状将移动,我们将抓住鼠标。我已经创建了一个椭圆形和给定大小的椭圆形图形。但我无法反复移动这种形状。我想我需要使用计时器类。我自己已经尝试了2个小时,但我还没有做到。

代码;

    import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;


import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.JPanel;



public class myshapestry extends JFrame implements ActionListener  {

JFrame frame=new JFrame("Deneme");
Container l ;
private static int ballX=150;
private static  int ballY=150;
myshapestry() {
     l=this.getContentPane();
     l.setLayout(null);
     MyPanel panel=new MyPanel();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.add(panel);
        frame.setVisible(true);
        frame.setSize(getPreferredSize());``

 }
 public Dimension getPreferredSize() {
       return new  Dimension(500,600);
   }
   public static void main (String args[]){
       myshapestry tr=new myshapestry();
       tr.setTitle("Game of Shapes");


   } 

   private static class MyPanel extends JPanel {
       protected void paintComponent(Graphics g){
           super.paintComponent(g);
           g.fillOval(ballX, ballY,50 , 70);

    }

       public void actionPerformed(ActionEvent e){
          ballX = ballX + 5;
          ballY = ballY + 10;
          repaint();
      }

       }

   }

我在myshapestry代码块中尝试了这些代码;

Timer timer=new Timer(100,myshapestry);
t.start();

1 个答案:

答案 0 :(得分:3)

添加类似这样的内容

return this

javax.swing.Timer timer=new javax.swing.Timer(100, panel) ; timer.start(); timer调用actionPerformed()方法每100毫秒