Width and Height of a Jpanel

Hi , i’ve a problem with the collision with Panel borders …
I post a part of code for every class :
in main class:

 
GamePanel_1 g = new GamePanel_1();
add(g);
pack();

in Panel class:

 
public static Dimension size= new Dimension(180,180);
setPreferredSize(size);

in a other class:


if(x>160){
collide=true;
isrunning=false;
x=160;
}

160 is a number calculate like the width of the panel set with setpreferredsize minus the width of my image (20 pixel), the problem is that is like if the panel haven’t the size that I’ve set and so the collision don’t work well

Someone could help me ??

I don’t quite understand your question…you have problems setting the size of the JPanel? What do you mean by “collision”?

No , I set the screen like 180X180 and i ve an image 20X20 pixel , I move the image on the screen … when x of image is 160 = panelsize(180)-widthofobject(20) i set x=160 so in this way the image should stay in the window… Instead overstep the window…

I don’t see anything wrong with the code per se in regards to what you’re wanting to do. Are you sure

if(x>160){
collide=true;
isrunning=false;
x=160;
System.out.println("Collision!!!"); // poor mans debugging
}

is being called?

He’s probably having a problem with the panel over-filling (for lack of a better term) the JFrame he is using. Run this code:

public static void main(String[] a) {
	JFrame j = new JFrame();
	JPanel p = new JPanel() {
		@Override
		public void paint(Graphics g) {
			g.clearRect(0, 0, getWidth(), getHeight());
			g.setColor(Color.red);
			g.drawRect(0, 0, getWidth(), getHeight());
		}
	};
	p.setPreferredSize(new Dimension(180, 180));
	p.setBackground(Color.black);
	j.add(p);
	j.pack();
	j.setVisible(true);
}

No matter how you resize the window, you can never see the JPanel’s right or bottom border.

So some reason they are 1 pixel out of bounds, and there are probably lots of fixes, but here is a quick one:

  • Set Panel prefferedSize(w + 1, h + 1)
  • Render up to getWidth() - 1 and getHeight() - 1

There is also probably some things you could do with a layout manager, but I haven’t fiddled with Swing in ages, so I don’t want to try and figure it out right now.