This article describes the simulation of planetary motion implemented by Java programming. Share it for your reference, as follows:
The Java language programming that I had been looking forward to for a long time has also come to an end. In a few months, I have basically mastered the simple usage of Java, learned the main basic knowledge of Java, object-oriented thinking, multi-threaded concurrency control, swing interface design, animation production, etc. Finally, I plan to create a course design that can cover as much of the knowledge learned as possible and connect it in series. Therefore, I have considered implementing a simple software to simulate planetary motion. The main ideas are as follows:
Animation is used to simulate planetary motion. There is a central planet in the main panel, and an elliptical orbit is drawn, and a moving planet is moving around the central planet. At the same time, there are four buttons set in the lower right corner, namely "Start", "Pause", "accelerate" and "decelerate" that can cause planets to move, pause, accelerate and decelerate respectively.
1. Class design:
Star inherits from JPanel. The Star class is the base class of planets, and all moving planets are inherited from the Star class. The internal draw() method mainly draws a solid circle, and the purpose is to ensure that the central planet always displays every time it is drawn. The paintComponent() method overrides the JPanel drawing method, aiming to ensure that instance objects of Stars class inherited from the Star class can draw their own planets. as follows:
package Star;import java.awt.Color;import java.awt.Graphics;import javax.swing.JPanel;public class Star extends JPanel{ /** * Basic planetary class*/ private static final long serialVersionUID = 1L; int x,y; int width,height; public Star() { width = 10; height = 10; } public Star(int x, int y){ this.x = x; this.y = y; width = 10; height = 10; } public void draw(Graphics g){ g.setColor(Color.blue); g.fillOval(x, y, width, height); } protected void paintComponent(Graphics g){ super.paintComponent(g); g.fillOval(x, y, width, height); }}The Stars class inherits from the Star class, which is a further refinement of the Star class, representing moving planets. The alfa in the Stars class represents the starting angle of the moving planet, and the speed represents the speed of the movement, which can be modified. Long and Short represent the major axis and minor axis of the elliptical trajectory respectively. The center represents the central planet of its instantiated object. The paintComponent() function overrides paintComponent(), internally refers to the draw() function of the parent class, and draws the elliptical track according to Long, Short, and Long and Short are determined by the instantiation object calling the constructor. The move() function describes the change equation of x and y, that is, changes around the elliptical orbit, and also specifies the way alfa changes. The start() function indicates the start of the thread, the pause() function indicates the thread pause, the acceleration() function indicates the acceleration operation on the planet, and the decelerate() function indicates the operation on the planet's deceleration.
The purpose of the Pthread class is to control threads, that is, the initial motion, pause motion, accelerate, and decelerate of the planet through instantiation of the Pthread class. The Pthread class inherits from the Thread class and is included in the Starts class. Therefore, the PThread class cannot be defined as a common class. The PThread class provides a run() method, constantly calls the repaint() method to repaint the picture. The setsuspend() method uses changing the boolean variable to pause the thread (call the notifyall() method). Because the Pthread class is an internal class of Starts, an object of the PThread class will be generated in the Starts class and the thread will be operated using this object.
The design is as follows:
package Star;import java.awt.Color;import java.awt.Graphics;public class Stars extends Star{ /** * Moving planet*/ private static final long serialVersionUID = 1L; double alfa ; double speed ; Star center; int Long ; //Darken axis int Short;//Short axis public Stars(int Px,int Py,Star center){ super(Px,Py); this.center = center; Long = (Px - center.x)*2; Short = (Py - center.y)*2; this.setOpaque(true);// move(); alfa = 0; speed = 0.001; } protected void paintComponent(Graphics g){ super.paintComponent(g); center.draw(g);//Draw the center point move(); g.setColor(Color.GREEN); g.drawOval(center.x-Long/2, center.y-Short/2, Long, Short); } public void move(){ x = center.x + (int)(Long/2*Math.cos(alfa)); y = center.y + (int)(Short/2*Math.sin(alfa)); //Run alfa along the elliptical trajectory += speed; //The angle is constantly changing} class PThread extends Thread{ //Repaint thread class private boolean suspend = true; private String control = ""; public void run(){ while(true){ synchronized (control) { if(suspend){ //move(); repaint(); } } } } public void setssopend(boolean s){ //Set thread pause method if (!suspend) { synchronized (control) { control.notifyAll(); } } this.suspend = s; } } public PThread pt = new PThread(); public void start(){ pt.setsuspend(true); pt.start(); } public void pause(){ pt.setsuspend(false); } public void accelerate(){ //Accelerate method if(speed > 0){ //Angle acceleration 0.0002 speed += 0.0002; } else speed = 0.001; } public void decelerate(){ //Decelerate method if(speed > 0){ speed -= 0.0002; //Deceleration at each angle 0.0002 } //If the speed is decelerated to 0, you cannot continue to decelerate. The speed is 0. Stop motion else speed = 0; }}The StarFrame class is the startup panel of this program. By instantiating this class, the main program interface is generated, and planetary components, buttons, and labels are added to the panel. The internal getPanel() method sets the two buttons and returns a JPanel (adds four buttons into the JPanel). The getLabel() method returns a JLabel with a literal description. The Center object is an instantiation of the Star class, and p1 is an instantiation of the Stars class, representing the central planet and the orbiting planet respectively. jb1, jb2, jb3, and jb4 are the control buttons for starting, pausing, accelerating and deceleration of the planet respectively. image represents the interface background image, and LayeredPanel is the hierarchical panel of the interface, which facilitates the setting of background image. jp,jl is the component that sets the background image. The design is as follows:
package Star;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JLayeredPane;import javax.swing.JPanel;public class StarFrame extends JFrame{ /** *Planetary simulation startup panel*/ private static final long serialVersionUID = 1L; Star center = new Star(300,200);//Define the center planet Stars p1 = new Stars(300+230,200+130,center);//The planet surrounding the center Stars p2 = new Stars(300+230+20,200+130+20,p1); JButton jb1 = new JButton("start"); JButton jb2 = new JButton("pause"); JButton jb3 = new JButton("accelerate"); JButton jb4 = new JButton("decelerate"); ImageIcon image=new ImageIcon("timg.jpg");// Background image, use relative path to define JLayeredPane layeredPane; //Define a hierarchical panel for placing background images JPanel jp; JLabel jl; public StarFrame(){ //Set position for p1, and size p1.setBounds(40,40,600,400); // p2.setBounds(40,40,600,400); //Define the background image, place the background image in JLabel, place the JLabel in JPanel layeredPane = new JLayeredPane(); jp = new JPanel(); jp.setBounds(0,0,image.getIconWidth(),image.getIconHeight()); jl=new JLabel(image); jp.add(jl); //Put jp to the bottom layer. layeredPane.add(jp,JLayeredPane.DEFAULT_LAYER); //Put jb to the first floor layeredPane.add(p1,JLayeredPane.MODAL_LAYER); // layeredPane.add(p2,JLayeredPane.MODAL_LAYER); layeredPane.add(getPanel(),JLayeredPane.MODAL_LAYER); layeredPane.add(getLabel(),JLayeredPane.MODAL_LAYER); layeredPane.add(getLabel(),JLayeredPane.MODAL_LAYER); //Set related actions for jb1, jb2, jb3, and jb4, respectively, jb1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub p1.start(); } } ); jb2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub p1.pause(); } }); jb3.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub p1.accelerate(); } }); jb4.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub p1.decelerate(); } }); this.setLayeredPane(layeredPane); this.setTitle("Star"); this.setBounds(100,100,1000,600); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } private JPanel getPanel(){ //Return the four buttons defined JPanel jp = new JPanel(); jp.add(jb1); jp.add(jb2); jp.add(jb3); jp.add(jb4); jp.setBounds(750,450,200,70); return jp; } private JPanel getLabel(){ //Return the text description JLabel jl = new JLabel("Planetary Simulation"); jl.setForeground(Color.RED);//Set the font color jl.setFont(new Font("Dialog",0,20));//Set the font JPanel jp = new JPanel(); jp.add(jl,BorderLayout.CENTER); jp.setBounds(800,0,150,40); return jp; } public static void main(String[] args) { @SuppressWarnings("unused") StarFrame f = new StarFrame(); }}Running effect:
2. Object:
Because Java is an object-oriented language, of course, it cannot be implemented by functions just like C language. How can there be no objects in the course structure?
Main objects:
object center, i.e. central planet
Object p1, orbiting the planet
Object pt, that is, the object responsible for controlling the thread
Object f, i.e. the program startup panel
3. Relationship between objects (interaction)
The relationship between p1 and center: The Star class is the base class of the planet, inherited from JPanel, and the basic radius and coordinates are defined internally. In fact, the instantiated object center is the center of the moving planet. The Stars class inherited from Star represents a moving planet, which is a further refinement. Therefore, the instantiation object p1 represents a moving planet 1 and moves around the center. At the same time, the center is passed as a parameter to p1 to complete the interaction between the two. This is the relationship between object p1 and center. After instantiating the object center, a solid circle will be drawn under the specified coordinates, and the x and y coordinates of the center object will not change. On the basis of drawing a solid circle, object p1 draws the elliptical orbits of the specified major axis and minor axis according to the center's coordinates. At the same time, it implements the Thread class internally, which does not interrupt the execution thread. The mutual inheritance relationship allows center and p1 to draw graphs without interfering with each other. It is worth mentioning that in the paintComponent() method in the Stras class, the draw() method of the center object still needs to be called, because the thread will call the repaint() method at the beginning. If the center's draw() method is not implemented, the final result will not show the central planet.
The relationship between pt and p1: The PThread class inherits from the Thread class and defines the run() method. By instantiating the object p1, the start() method can be called to start the thread. The PThread class is inside the Starts class, so the thread can be controlled through the methods in p1, that is, it can control its speed, accelerate and decelerate, and control whether it runs or not.
The relationship between f and each object: StarFrame inherits from JFrame. In fact, the instantiation object f adds each object into the canvas, creates an interface, and controls the size and position of each component, which is the key to the program's operation.
4. Object-oriented understanding:
Everything is an object. Some students asked me what the object is. I replied that those with new are objects, and objects are instantiation of classes. In this program, countless planets can be created by instantiating the Stars class (theoretically, yes). However, some problems in the implementation of internal functions are difficult to solve. The main thing is to rewrite the paintComponent() method. After creating the object again, the method will be rewrite again, so an inevitable problem will occur, which is also a regret that cannot be solved!
For more Java-related content, readers who are interested in this site can view the topics: "Introduction and Advanced Tutorial on Java Object-Oriented Programming", "Tutorial on Java Data Structure and Algorithm", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.