第一次在这里发帖,如果我完全不了解所有规则,请原谅我。
我有一些问题,我是 Java 的新手,之前阅读过这个社区并从中获得了一些帮助。
我目前在 JFrame 上绘制多个球时遇到问题,我从其他学生那里得到了一些解决方案,但没有成功。一个学生现在已经开始工作了,但是通过在 Frame 类中绘制我认为不正确的所有内容,并将 repaint() 放在 paint() 中,这也感觉不对。如果有人能指出我正确的方向,我将不胜感激。
丹尼尔
代码: 游戏Java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myanimie;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
*
* @author Dan
*/
public class Game extends JFrame implements Runnable {
private Ball myBall = new Ball();
private Paddle myPad = new Paddle();
final JPanel jp = new JPanel();
final JPanel jp1 = new JPanel();
final JPanel jp2 = new JPanel();
public Game()
{
setVisible(true);
setResizable(false);
setTitle("First Test Animation");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setSize(640,480);
}
public void run()
{
move();
}
public void paint(Graphics g)
{
super.paint(g);
myBall.paint(g);
}
public void move()
{
myBall.start();
repaint();
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
System.exit(0);
}
}
}
Ball.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myanimie;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.geom.Ellipse2D;
/**
*
* @author Dan
*/
public class Ball extends Thread {
Point pos;
Color ballColor = Color.red;
Color[] ts = {Color.CYAN,Color.green,Color.black};
private int yChange = 2;
private int xChange = 1;
public Ball()
{
pos = new Point();
pos.x = (int)(Math.random() * (500 - 100)) + 10 ;
pos.y = (int)(Math.random() * (500/2 - 100)) + 10;
}
@Override
public void run()
{
while(true)
{
move();
}
}
public void paint(Graphics g)
{
g.setColor(ballColor);
g.fillOval(pos.x - 10, pos.y - 10, 60,60);
}
public void move()
{
// System.out.println("y " + pos.y);
// System.out.println("x " + pos.x);
if(pos.y < 20)
{
yChange = -yChange;
System.out.println("T");
ballColor = Color.BLUE;
}
if(pos.x < 20)
{
xChange = -xChange;
System.out.println("L");
ballColor = Color.MAGENTA;
}
if(pos.x > 620 - 20)
{
xChange = -xChange;
System.out.println("R");
ballColor = Color.GREEN;
}
if(pos.y > 430 - 20)
{
yChange = -yChange;
System.out.println("B");
ballColor = Color.PINK;
}
if(pos.y < 640 - 20)
{
pos.translate(xChange, yChange);
}
if(pos.x < 480 - 20 || pos.x > 460)
{
pos.translate(xChange, yChange);
}
}
public Point getPosition()
{
return pos;
}
public Ellipse2D area()
{
return new Ellipse2D.Double(pos.x, pos.y,60,60);
}
}
这是我糟糕的代码,我已经解决了错误但没有动画 atm。
谢谢大家!!你的洞察力是无价的
最佳答案
“并将 repaint() 放在 paint() 中”听起来很危险!
repaint()
方法会尽快调用此组件的 paint 方法。
您可能会详细说明如何尝试在框架上绘制“多个”球。如果没什么特别的,你的答案可能是here
关于Java Paint() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6655743/