我正在尝试使用Netbeans创建一个带有两个球的java程序(一个位于顶部,另一个位于底部),执行时它们向相反的方向移动并离开屏幕。
原始代码是使用一个球给我们的,我们被要求添加第二个面板,因此代码中的混淆。
我的问题是当我使用BoxLayout.Y_AXIS
执行代码时,球会在中心相遇并因面板排列而消失。我希望球从中心穿过其他面板。
我尝试过使用border layout
,但我丢了一个球。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RandomBall {
JFrame frame;
public int x = 0;
public int y = 0;
public int z = 300;
public int deltaX;
public int deltaY;
public int deltaZ;
public int posNeg;
public int diameter = 50;
final static public int MULT = 5;
Ball1DrawPanel drawPanel1;
Ball2DrawPanel drawPanel2;
JPanel pan;
public static void main(String[] args) {
RandomBall gui = new RandomBall();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel1 = new Ball1DrawPanel();
drawPanel2 = new Ball2DrawPanel();
pan = new JPanel();
pan.setLayout(new BoxLayout(pan, BoxLayout.Y_AXIS));
pan.add(BorderLayout.NORTH, drawPanel1);
pan.add(BorderLayout.SOUTH, drawPanel2);
frame.getContentPane().add(BorderLayout.CENTER, pan);
frame.setSize(500, 500);
frame.setVisible(true);
deltaX = (int) (Math.random() * MULT); //randomly set the displacement in the x direction (across)
deltaY = (int) (Math.random() * MULT); //randomly set the displacement in the y direction (down)
deltaZ = (int) (Math.random() * MULT); //randomly set the displacement in the y direction (down)
while ((deltaX == 0) && (deltaY == 0)) {
deltaX = (int) (Math.random() * MULT); //to prevent both values being zero - ball will not move
deltaY = (int) (Math.random() * MULT);
deltaZ = (int) (Math.random() * MULT);
}
posNeg = (int) (Math.random() * 2);
if (posNeg == 0) {
deltaX = deltaX * -1; //randomly set the direction to left or right
}
}
public RandomBall() {
go();
}
class Ball1DrawPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
g.setColor(Color.red);
g.fillOval((this.getWidth() + (x) - diameter) / 2, (0 + (y)) / 2, diameter, diameter);
frame.repaint();
x = x + deltaX;
y = y + deltaY;
}
}
class Ball2DrawPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
g.setColor(Color.BLUE);
g.fillOval((this.getWidth() + (x) - diameter) / 2, (0 + (z)) / 2, diameter, diameter);
frame.repaint();
x = x + deltaX;
z = z - deltaZ;
}
}
}
是否有任何layout
,或任何实现,我可以使用,这将允许球进入相对的小程序,而不是在与另一个碰撞时在中心处打破?
答案 0 :(得分:0)
我感谢所有的帮助,但做了一些研究并设法找到我的问题的解决方案..
我创建了第二个面板,
pan = new JPanel();
pan.setLayout(new OverlayLayout(pan));
在此之后,我刚将两个球添加到“平底锅”面板和VOILAAAA ..
再次感谢所有帮助..
答案 1 :(得分:-3)
我的建议: