简体   繁体   中英

Java swing 2D gravity simulation not working

I have this code for a gravity simulation, where the player can hold the mouse clicked to create planets (the longer he holds the mouse pressed, the bigger it is) at the mouse position for up to 100 planets.

But my problem is, that the planets are succesfully created, but arent displayed.

Code :

import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.Arrays;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Point;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

class Planet {
     public float x;
     public float y;
     public float w;
     public float xv;
     public float yv;
     public Planet(float xn,float yn,float wn,float xvn,float yvn) {
         x=xn;
         y=yn;
         w=wn;
         yv=yvn;
         xv=xvn;
     }
     public float distance(Planet planet) {
         float xdis=x-planet.x;
         float ydis=y-planet.y;
         return (float)Math.sqrt((xdis*xdis)+(ydis*ydis));
     }
     public void move() {
         x=x+xv;
         y=y+yv;
     }
     public void gravity(Planet[] objects,float intensity) {
         Planet planet;
         float distancec;
         float gravity;
         for (Planet obj:objects) {
              if (obj != null) {
                  if (obj.equals(this)==false) {
                      planet=obj;
                      distancec=distance(planet);
                      gravity=distancec*(planet.w/intensity);
                      xv=xv+((x-planet.x)*gravity);
                      yv=yv+((y-planet.y)*gravity);
                      if (distancec < w+planet.w) {
                          //Probably bump off or unite...
                      }
                  }
              }
              else {
                  break;
              }
         }
     }
}
public class Gravity extends JFrame implements MouseListener, KeyListener, MouseWheelListener {
     public int[] mouse=new int[5];
     public Planet[] planets=new Planet[100];
     public void mousePressed(MouseEvent m) {
         if (m.getButton() == m.BUTTON1) {
             mouse[2]=1;
         }
         if (m.getButton() == m.BUTTON1) {
             mouse[4]=1;
         }
    }
    public void mouseClicked(MouseEvent m) {
         if (m.getButton() == m.BUTTON1) {
             mouse[2]=3;
         }
         if (m.getButton() == m.BUTTON1) {
             mouse[4]=3;
         }
    }
    public void mouseReleased(MouseEvent m) {
         if (m.getButton() == m.BUTTON1) {
             mouse[2]=2;
         }
         if (m.getButton() == m.BUTTON1) {
             mouse[4]=2;
         }
    }
    public void mouseEntered(MouseEvent m) {
    }
    public void mouseExited(MouseEvent m) {
    }
    public void mouseWheelMoved(MouseWheelEvent w) {
         mouse[3]=w.getWheelRotation();
    }
     public void keyTyped(KeyEvent e) {

     }
     public void keyReleased(KeyEvent e) { 

     }
     public void keyPressed(KeyEvent e) {

     } 
     public Gravity(){
          super("Gravity");
          requestFocus();
          addKeyListener(this);
          addMouseListener(this);
          setTitle("Gravitation");
          setContentPane(new Zeichenflaeche());

          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

          setSize(800, 600);

          setResizable(true);

          setVisible(true); 
          while (true){
              repaint();
              try {
              Thread.sleep(33);
              } catch(InterruptedException bug) {
              Thread.currentThread().interrupt();
              System.out.println(bug);
              }
              mouse[0]=MouseInfo.getPointerInfo().getLocation().x-getComponents()[0].getLocationOnScreen().x;
              mouse[1]=MouseInfo.getPointerInfo().getLocation().y-getComponents()[0].getLocationOnScreen().y;
              repaint();
          }
     }


     class Zeichenflaeche extends JPanel{
        public boolean dragging;
        public float w;
        public Zeichenflaeche() {
        }
        public void reset_mouse_state() {
         mouse[2]=0;
         mouse[3]=0;
         mouse[4]=0;
        }
        public void paintComponent(Graphics g){

             if (mouse[2]==1) {

                 dragging=true;
             }
             if (dragging==true) {
                 w++;
             }
             if (mouse[2]==2 || mouse[2]==3) {
                 dragging=false;
                 System.out.println("Append Planet");
                 for (Planet planeti:planets) {
                      if (planeti == null) {
                          planeti=new Planet(mouse[0],mouse[1],w,0,0);
                          System.out.println("Planet succesfully appended");
                          System.out.println(Arrays.toString(new float[] {planeti.x,planeti.y,planeti.w}));
                          break;
                      }
                 }
                 w=1;
             }
         for (Planet planeti:planets) {
              try {
                  g.setColor(Color.GREEN);
                  g.fillOval((int)planeti.x-(int)planeti.w,(int)planeti.y-(int)planeti.w,(int)planeti.w*2,(int)planeti.w*2);
                  planeti.gravity(planets,10);
                  planeti.move();
              }
              catch (Exception bug) {
              }
         }
         reset_mouse_state();
        }   
     }
     public static void main(String args[]){
            new Gravity();
     }
}

Thanks for any help.

In your for-each loop, you are assigning a new Planet to the local variable planeti (local to the for-each loop, discarded afterwards), so this has no use.

You should replace this loop with a for loop, so that you can assign your Planet to the current index of the array.

So replace this loop :

         for (Planet planeti:planets) {
              if (planeti == null) {
                  planeti=new Planet(mouse[0],mouse[1],w,0,0);
                  System.out.println("Planet succesfully appended");
                  System.out.println(Arrays.toString(new float[] {planeti.x,planeti.y,planeti.w}));
                  break;
              }
         }

with this loop :

        for (int i=0;i<planets.length;i++) {

              Planet currentPlanet = planets[i];

              if (currentPlanet == null) {

                  Planet newPlanet = new Planet(mouse[0],mouse[1],w,0,0);
                  planets[i] = newPlanet; 
                  System.out.println("Planet succesfully appended");
                  System.out.println(Arrays.toString(new float[] {newPlanet.x,newPlanet.y,newPlanet.w}));
                  break;
              }
         }

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