java - 如何移动 JFrame 形状

标签 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();

最佳答案

添加这样的内容

javax.swing.Timer timer=new javax.swing.Timer(100, panel) ;
timer.start();

每 100 毫秒,timer 就会调用 MyPanel 类的 actionPerformed() 方法

关于java - 如何移动 JFrame 形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30954570/

相关文章:

Java BoxLayout 对齐问题

iOS UIImageView 旋转后消失 M_PI_4

java - "Java"做动画的方式

java - 存储字符串数组唯一列表的最佳方式

Java Spring——验证单个对象字段

java - 考虑不同的屏幕分辨率和字体创建 JFace 对话框的理想方式

javascript - 为什么我用rotateY(180deg)时有时间空白

java - 使用 TestNG 为 WebDriver 创建 Maven 项目时出现 Maven 错误 "Archetype catalog is empty"

java调整大小的方法

java - JFrame 的半透明加载覆盖