How to move JFrame shape

冷暖自知 提交于 2019-12-12 02:58:28

问题


I'm trying to develop a simple game. The games is about the shapes. Shapes will move and we'll catch by mouse. I have already created a oval and given size of oval graphic. But I cannot move this shape repeatedly. I think I need to use timer class. I have been trying 2 hours myself but I didnt do yet.

The code;

    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();
      }

       }

   }

I was trying these code in the myshapestry code block;

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

回答1:


Add something like this

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

Each 100msec the timer invokes actionPerformed() method of your MyPanel class



来源:https://stackoverflow.com/questions/30954570/how-to-move-jframe-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!