1

I am trying to make a basic layout for 2D games, everyone says add objects to JPanel and then add the panel to JFrame but ther is still only one object displayed at a time here is my code

I have a rectangle point and ball class but they are all working the problem is JPanel only displaying the first object added

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;

public class test{
    public static void main (String[] args) throws InterruptedException {
        JFrame frame = new JFrame("PONG.s'aight");
        JPanel panel = new JPanel(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(0,0,800,500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        Ball a = new Ball (100,100,5,5);
        Ball b = new Ball(200,200,15,15);
        panel.add(a);
        panel.add(b);
        frame.getContentPane().add(panel, BorderLayout.CENTER);

        /*if(b.isCollide(paddle)) b.reverse(Direction.x);*/

        while(true){
            if(b.x==770)b.reverse(Direction.x);
            if(b.x==0)b.reverse(Direction.x);
            if(b.y==450)b.reverse(Direction.y);
            if(b.y==0)b.reverse(Direction.y);
            if(b.x==770)a.reverse(Direction.x);
            if(b.x==0)a.reverse(Direction.x);
            if(b.y==450)a.reverse(Direction.y);
            if(b.y==0)a.reverse(Direction.y);
            b.moveGen();
            a.moveGen();
            frame.repaint();
            Thread.sleep(2);
        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
william
  • 11
  • 1
  • 1
    Just so you know, the `while-loop` is a bad idea and could potentially block the Event Dispatching Thread. Also, the `JPanel` is using a `FlowLayout` which means that any modifications you might make to the size and position of the components could be overridden at any time. This is also, likely, part of your problem. When you add each `Ball` to the `JPanel`, it's size and position are been calculated by the `FlowLayout` – MadProgrammer Feb 26 '15 at 01:15
  • 2
    Take a look at [this example](http://stackoverflow.com/questions/13022754/java-bouncing-ball/13022788#13022788) for a different way to achieve what you are trying to do, which will give you more control. You're probably also going to need to take a look at [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) and [Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/) – MadProgrammer Feb 26 '15 at 01:16

0 Answers0