[英]How to create a Graphics object to draw shapes on JFrame
我想制作一個使彈丸動畫化的程序(一個以2D形式在彈丸中飛行的球)。 在主程序中,我調用了一個Shoot()函數,其參數為Graphics對象,但是我不知道如何創建該對象,以便它可以在我的JFrame對象上繪制。 請幫我。
import java.lang.Math;
import java.applet.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Projectile extends JPanel{
public static int ScreenH=1500;
public static int ScreenW=3000;
public static int Xcor=0;
public static int Ycor=0;
public static int ballRadius=20;
public static int prevXcor = 0;
public static int prevYcor = 0;
public static int newXcor = 0;
public static int newYcor = 0;
public static int Time = 0;
public static int Angle = 45;
public static int Velocity = 10;
public static double Acceleration = 9.8;
public static void InitGraphics(){
JFrame jframe = new JFrame();
jframe.setTitle("Projectile");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(ScreenW, ScreenH);
jframe.setResizable(false);
jframe.setVisible(true);
jframe.add(new Projectile());
}
public static void drawCenteredCircle(Graphics g, int x, int y) {
int a = x;
int b = 1000 - y;
g.fillOval(a,b, ballRadius, ballRadius);
}
public static void move() throws InterruptedException {
Thread.sleep(20);
Time += 20;
double XVelocity = Math.sin(Velocity);
double YVelocity = Math.cos(Velocity);
int X = (int) (XVelocity*Time);
int Y = (int) ((YVelocity*Time) + (0.5*Acceleration*Time*Time));
newXcor = X;
newYcor = Y;
}
public static void repaint(Graphics g) {
g.setColor(Color.white);
drawCenteredCircle(g, prevXcor, prevYcor);
g.setColor(Color.red);
drawCenteredCircle(g, newXcor, newYcor);
prevXcor = newXcor;
prevYcor = newYcor;
}
public static void Shoot(Graphics g) throws InterruptedException {
while ( (newXcor < (ScreenW - (4*ballRadius))) && (newYcor < (ScreenH - (4*ballRadius)))) {
move();
repaint(g);
}
}
public static void main(String[]args) {
InitGraphics();
Shoot();
}
}
JFrame只是窗口,您需要向其添加一個JComponent。 JComponents包含一個protected void paintComponent(Graphics g)
方法,您需要像這樣重寫它:
JFrame frame = new JFrame();
JComponent canvas = new JComponent() {
protected void paintComponent(Graphics g) {
//call repaint(g) here instead of this
g.setColor(Color.RED);
g.fillRect(0, 0, getWidth(), getHeight());
};
};
frame.add(canvas);
您可能需要清除重塗背景
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.