简体   繁体   中英

JPanel and JFrame coordinate messed up

I am trying to write a game using JPanle and JFrame. I set up a panel inside a frame. When I paint on the panel with a rectangle size of the panel at 0,0. The rectangle shifts up and left for some pixels. How do I fix this problem? I googled and I saw the insets method, but I don't want to use that calculate my coordinate everytime I draw.

Here are the codes

public class Game extends JFrame{

public Game(){
    this.getContentPane().setPreferredSize(new Dimension(800,600));  
    pane p = new pane();
    this.getContentPane().add(p,BorderLayout.CENTER);
    p.setPreferredSize(new Dimension(800,600));
    pack();
    setResizable(false);
    setVisible(true);


}


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

}

public class pane extends JPanel{

public pane(){

setDoubleBuffered(false);
setBackground(Color.black);
setPreferredSize( new Dimension(800, 600));

setFocusable(true);
requestFocus(); 
}

@Override
public void paint(Graphics g) {
    g.setColor(Color.white);
    g.fillRect(0, 0, 800, 600);
    g.setColor(Color.black);
    g.fillRect(0, 0, 800, 600);

}
}

screen shot link

Actually there is no shift of your panel, it is located in 0,0. The problem is that the panel actually gets a size of 810,610 instead of 800,600. For some reason (which so far I was unable to find and if somebody has an idea I would love to learn), when you call setResizable(false) on a JFrame , its insets are modified and eventually this leads to your content pane to be bigger than expected (at least on JDK6/Win7). Call setResizable(false) before adding the components and packing the frame, and it works.

Also consider painting a rectangle of the size of your panel ( g.fillRect(0, 0, getWidth(), getHeight()); so that you are sure to fill the entire area, no matter what happens.

Any reason to fill the background with white color and then replace it with black?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM