Netbeans を使用して、2 つのボール (上部と下部の 1 つの位置) を使用して Java プログラムを作成しようとしています。実行すると、それらは反対方向に移動して画面外になります。
元のコードは 1 つのボールを使用して提供され、2 つ目のパネルを追加するように求められたため、コード内で混乱が生じました。
私の問題はBoxLayout.Y_AXIS
、ボールが中央に集まり、パネルの配置が原因で消えるコードを実行するときです。ボールが中央を横切って他のパネルに入るようにします。
を使ってみborder layout
たのですが、ボールが1つ外れてしまいました。
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
ボールが他のアプレットと衝突したときに中央で壊れるのではなく、ボールが反対側のアプレットに交差できるようにするために使用できる、または実装はありますか?