两个弹跳java代码的球
大家好,我正在尝试创建一个包含两个球的程序。一个向右转,一个向下。我有一个密码,但我不知道如何让另一个球向下移动。。。任何帮助都是非常感谢的两个弹跳java代码的球,java,swing,java-2d,Java,Swing,Java 2d,大家好,我正在尝试创建一个包含两个球的程序。一个向右转,一个向下。我有一个密码,但我不知道如何让另一个球向下移动。。。任何帮助都是非常感谢的 import java.awt.*; import javax.swing.*; import java.awt.event.*; class move extends JPanel { Timer timer; int x = 0, y = 10, width = 40, height = 40; int radius = (width
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class move extends JPanel
{
Timer timer;
int x = 0, y = 10, width = 40, height = 40;
int radius = (width / 2);
int frXPos = 500;
int speedX = 1;
move()
{
ActionListener taskPerformer = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
if (x == 0)
{
speedX = 1;
}
if (x > (frXPos - width))
{
x=0;
}
x = x + speedX;
repaint();
}
};
timer = new Timer(2, taskPerformer);
timer.start();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(x, y, width, height);
}
}
class MovingBall
{
MovingBall()
{
JFrame fr = new JFrame("Two Balls Moving Other Ways");
move o = new move();
fr.add(o);
fr.setVisible(true);
fr.setSize(500, 500);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
MovingBall movingBall = new MovingBall();
}
}
不要试图使每个球成为一个组件,只需使用一个绘图曲面和一个保存/绘制/操纵每个球状态的ball类即可。然后有一个球对象列表。如图所示 该示例使用了许多“相同”类型的球,这些球移动相同。但是您可以做的是使用一个抽象方法
move()
,创建一个超级抽象类Ball
,并为每个类重写move()
方法
您还将在示例中注意到列表
是如何在paintComponent
方法中迭代的。这就是你应该做的
例如(在链接的示例上展开)
public interface Ball {
void drawBall(Graphics g);
void move();
}
public abstract class AbstractBall implements Ball {
protected int x, y, width, height;
...
@Override
public void drawBall(Graphics g) {
g.fillOval(x, y, width, height);
}
// getters and setters where needed
}
public class UpDownBall extends AbstractBall {
...
@Override
public void move() {
// change y position
}
}
public class RightLeftBall extends AbstractBall {
...
public void move() {
// change x position
}
}