Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Detect collision of shaped JPanels

KlighamMar 29 2010 — edited Mar 30 2010
I was wondering if it is possible to detect wheter JPanels are intersecting (collision). I know it can be done with the intersect function of Area package, but the problem is that I don't know how to get the shape of the JPanel into an area.

I have added a little SSCCE whith two JPanels that can be moved. I use the ComponentMover class which can be found here .
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test{

    private static JPanel panel;
    private JPanel testie, testie2;

    public Test(){

        testie = new JPanel(){

            @Override
            public void paintComponent(Graphics g){

                Graphics2D g2 = (Graphics2D) g;

                RoundRectangle2D r = new RoundRectangle2D.Double (0, 10.0, 50.0, 50.0, 5.0, 5.0);

                g2.fill(r);

                g2.draw(r);

            }
        };

        testie.setPreferredSize(new Dimension(50,50));
        JButton button = new JButton("Blue car");
        testie.add(button);

        ComponentMover cm = new ComponentMover(testie, button);

        testie2 = new JPanel(){

            @Override
            public void paintComponent(Graphics g){

                Graphics2D g2 = (Graphics2D) g;

                RoundRectangle2D r = new RoundRectangle2D.Double (0, 10.0, 50.0, 50.0, 5.0, 5.0);

                g2.fill(r);

                g2.draw(r);

            }
        };

        testie2.setPreferredSize(new Dimension(50,50));
        JButton button1 = new JButton("Red car");
        testie2.add(button1);

        ComponentMover cm1 = new ComponentMover(testie2, button1);

        panel = new JPanel();
        panel.setBackground(Color.red); 
        panel.add(testie);
        panel.add(testie2);
    }

  public static void main(String[] args) {
    new Test();

    JFrame frame = new JFrame();
    frame.getContentPane().add(panel);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setVisible(true);
  }
}
I tried to get shape with getBounds, but that only seems to work with a rectangle.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 27 2010
Added on Mar 29 2010
3 comments
1,162 views