问题描述
我已经制作了这个太阳系,到目前为止我已经完成了制作这个代码。 如图所示,我想使用 public static class SolarCv extends JComponent 而不是使用 public static class SolarCv extends JPanel,但它不起作用。我应该在代码中更改什么以及如何添加围绕对象的轨道,如图所示?
package solar;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.io.IOException;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class Orbit {
public static class SolarCv extends JComponent {
int width;
int height;
public SolarCv(int width,int height) {
this.width = width;
this.height = height;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(width,height);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
// Clear the background.
g2.setColor(getBackground());
g2.fillRect(0,getWidth(),getHeight());
// Sun transform. Just centre it in the window.
AffineTransform StarSun = AffineTransform.getTranslateInstance(getWidth() / 2,getHeight() / 2);
// Draw the sun
g2.setTransform(StarSun);
SuperStar(g2,80,Color.YELLOW);
// Orbital period.
// One rotation every 10s.
double percentRotation = System.currentTimeMillis() % 10000 / 10000.0;
// To radians.
double angle = -Math.PI * 2 * percentRotation;
// Earth transform.
// Set the orbital radius to 1/3rd the panel width
AffineTransform StarEarth = AffineTransform.getTranslateInstance(getWidth() / 4,0);
// Rotate
StarEarth.preConcatenate(AffineTransform.getRotateInstance(angle));
// Add the sun transform
StarEarth.preConcatenate(StarSun);
// Draw the earth
g2.setTransform(StarEarth);
SuperStar(g2,40,Color.BLUE);
// Moon transform.
// Set the orbital radius to 1/10th the panel width
AffineTransform StarMoon = AffineTransform.getTranslateInstance(getWidth() / 10,0);
// Rotate
StarMoon.preConcatenate(AffineTransform.getRotateInstance(angle));
// Add the earth transform (already includes the sun transform)
StarMoon.preConcatenate(StarEarth);
// Draw the moon
g2.setTransform(StarMoon);
SuperStar(g2,20,Color.DARK_GRAY);
}
private void SuperStar(Graphics2D g2,int size,Color color) {
g2.setColor(color);
g2.fillOval(-size / 2,-size / 2,size,size);
}
}
public static void main(String[] args) throws IOException,InterruptedException {
JFrame SolarSys = new JFrame("Orbit");
SolarSys.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JComponent SolarCv = new SolarCv(500,500);
SolarSys.add(SolarCv);
SolarSys.pack();
SolarSys.setVisible(true);
while (true) {
Thread.sleep(20);
SolarCv.repaint();
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)