I'm 'spose to be making a screen saver-ish program where objects bounce off the walls, but I'm stuck getting multiple objects to show up on the screen at once.

This is my object to make a square:

package movingshape;

import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.*;
import java.util.Random;

public class Shapes extends JPanel implements Runnable
{

    Random myR = new Random();
    int x_pos;
    int y_pos;
    int x_width = 62;
    int y_height = 60;
    int right=5;
    int left= -5;
    int up=-5;
    int down= 5;
    int width, height;
    boolean goDown, goRight;

    public Shapes(int x, int y)
    {
         x_pos = x;
         y_pos = y;
    }

//   public void init()
//	{
//
//	}

    public void start ()
    {

        Thread th = new Thread (this);
        th.start ();
    }

    @Override
    public void paintComponent( Graphics g )
    {
        super.paintComponent( g );

        g.setColor( Color.BLACK);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor( Color.GREEN);
        g.fillRect(x_pos, y_pos, x_width, y_height);

    }

    public void drawBall (int nx, int ny)
    {
        x_pos= nx;
        y_pos= ny;
        this.width=this.getWidth();
        this.height=this.getHeight();
        repaint();
    }

    public void run ()
    {

        goRight = true;
        goDown = true;

        while (true)
        {


            if(goRight)
            {
                x_pos += right;
                if (x_pos >= (getWidth() - x_width))
                    goRight = false;
            }
            else
            {
                x_pos += left;
                if ( x_pos <= 0)
                    goRight =  true;
            }

            if(goDown)
            {
                y_pos += down;
                if(y_pos >= getHeight()-y_height)
                    goDown = false;
            }
            else
            {
                y_pos += up;
                if(y_pos <= 0)
                    goDown = true;
            }
            drawBall(x_pos, y_pos);

            repaint();

            try
            {
                Thread.sleep (5);
            }
            catch (InterruptedException ex)
            {
                    // do nothing
            }


        }
    }
}

And this is my code to make the window and add the object:

package movingshape;
import javax.swing.JFrame;
/**
 *
 * @author Majeh
 */
public class Main {


   public static void main( String[] args ) throws InterruptedException
   {

      Shapes sq1 = new Shapes(10, 100);
      Shapes sq2 = new Shapes(50, 450);


        JFrame application = new JFrame();
        application.setBounds(0,0,sq1.getWidth(),sq1.getHeight());

        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        application.setTitle("Moving shape OMG");
        application.add( sq1 );
        application.setSize(700, 700);
        application.setVisible( true );
        sq1.start();


    }

}

That will allow me one moving square in my JPanel, how do I make multiple moving objects appear? The best I can do is have two squares that are constantly flashing, and sometimes the 2nd doesn't show up at all.

Recommended Answers

All 3 Replies

runnable doesn't makes miracles itsefl, you ahve to look for javax.swing.Timer,

for example (change Stars to the Balls)

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
//http://stackoverflow.com/questions/3256269/jtextfields-on-top-of-active-drawing-on-jpanel-threading-problems/3256941#3256941
public class AnimationBackground {

    public AnimationBackground() {
        Random random = new Random();
        JFrame frame = new JFrame("Animation Background");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLayout(new GridLayout(0, 1, 10, 10));
        //frame.setLayout(new GridLayout(0, 3, 10, 10));
        //for (int iPanels = 0; iPanels < 3; iPanels++) {
        for (int iPanels = 0; iPanels < 1; iPanels++) {
            final MyJPanel panel = new MyJPanel();
            panel.setBackground(Color.BLACK);
            for (int i = 0; i < 100; i++) {
                Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
                star.setColor(new Color(100 + random.nextInt(155), 100 + random.nextInt(155), 100 + random.nextInt(155)));
                star.setxIncr(-3 + random.nextInt(7));
                star.setyIncr(-3 + random.nextInt(7));
                panel.add(star);
            }
            panel.setLayout(new GridLayout(10, 1));
            JLabel label = new JLabel("This is a Starry background.", JLabel.CENTER);
            label.setForeground(Color.WHITE);
            panel.add(label);
            JPanel stopPanel = new JPanel();
            stopPanel.setOpaque(false);
            stopPanel.add(new JButton(new AbstractAction("Stop this madness!!") {

                private static final long serialVersionUID = 1L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    panel.stopAnimation();
                }
            }));
            panel.add(stopPanel);
            JPanel startPanel = new JPanel();
            startPanel.setOpaque(false);
            startPanel.add(new JButton(new AbstractAction("Start moving...") {

                private static final long serialVersionUID = 1L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    panel.startAnimation();
                }
            }));
            panel.add(startPanel);
            frame.add(panel);
        }
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                AnimationBackground animationBackground = new AnimationBackground();
            }
        });
    }

    class Star extends Polygon {

        private static final long serialVersionUID = 1L;
        private Point location = null;
        private Color color = Color.YELLOW;
        private int xIncr, yIncr;
        static final int WIDTH = 500, HEIGHT = 500;

        Star(Point location) {
            int x = location.x;
            int y = location.y;
            this.location = location;
            this.addPoint(x, y + 8);
            this.addPoint(x + 8, y + 8);
            this.addPoint(x + 11, y);
            this.addPoint(x + 14, y + 8);
            this.addPoint(x + 22, y + 8);
            this.addPoint(x + 17, y + 12);
            this.addPoint(x + 21, y + 20);
            this.addPoint(x + 11, y + 14);
            this.addPoint(x + 3, y + 20);
            this.addPoint(x + 6, y + 12);
        }

        public void setColor(Color color) {
            this.color = color;
        }

        public void move() {
            if (location.x < 0 || location.x > WIDTH) {
                xIncr = -xIncr;
            }
            if (location.y < 0 || location.y > WIDTH) {
                yIncr = -yIncr;
            }
            translate(xIncr, yIncr);
            location.setLocation(location.x + xIncr, location.y + yIncr);
        }

        public void setxIncr(int xIncr) {
            this.xIncr = xIncr;
        }

        public void setyIncr(int yIncr) {
            this.yIncr = yIncr;
        }

        public Color getColor() {
            return color;
        }
    }

    class MyJPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        private ArrayList<Star> stars = new ArrayList<Star>();
        private Timer timer = new Timer(20, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                for (Star star : stars) {
                    star.move();
                }
                repaint();
            }
        });

        public void stopAnimation() {
            if (timer.isRunning()) {
                timer.stop();
            }
        }

        public void startAnimation() {
            if (!timer.isRunning()) {
                timer.start();
            }
        }

        @Override
        public void addNotify() {
            super.addNotify();
            timer.start();
        }

        @Override
        public void removeNotify() {
            super.removeNotify();
            timer.stop();
        }

        MyJPanel() {
            this.setPreferredSize(new Dimension(520, 520));
        }

        public void add(Star star) {
            stars.add(star);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            for (Star star : stars) {
                g.setColor(star.getColor());
                g.fillPolygon(star);
            }
        }
    }
}

Oh god...you just broke my brain completely. Good sir, can you break that down to retard-speak for me?

hehehe, good one, be sure that not possible to learnt per one day, month, hmmm little bit longer ...

once day (half year) I started with same results

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.