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.