Question

I am currently working on a project to make Connect 4 and I'm running into some problems with the coordinate system for it. I have an 800x600px png image which shows the 'board' and it is made up of an 8x6 grid with each location being a 100x100px square...at least that's how it is in GIMP2 and in the filesystem. However when I use Graphics2D's drawImage() method to paint the image onto a 800x600 JFrame it sticks off the bottom. Do I need to account for the JFrame's borders and stuff in this system, or am I missing something else?

Thanks!

P.S. Here is the JPanel class that does the drawing.

public class GameBoard extends JPanel { 
public GameBoard() {
}

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    //Write messages
    if (!(GameManager.getInstance().getMessage() == null)) {
        g2d.drawString(GameManager.getInstance().getMessage(), 400, 25);
    }


    //Draw board graphic        
    ImageIcon bg = new ImageIcon("res/board.png");
    g2d.drawImage(bg.getImage(), 0, 0, 800, 600, this);

    //Draw counters


    for (int columns = 0; columns < 8; columns++) {
        for (int rows = 0; rows < 6; rows++) {
            if (!(GameManager.getInstance().getState(columns, rows) == null)) {
                Counter cTemp = GameManager.getInstance().getState(columns, rows);
                g2d.drawImage(cTemp.getImage(), cTemp.getX(), cTemp.getY(), 100, 100, this);
            }                   
        }
    }       
}

}

Was it helpful?

Solution

  1. Override paintComponent instead of paint and call super.paintComponent(g)

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        ...
    }
    
  2. Override getPreferredSize() for your JPanel

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(800, 600);
    }
    
  3. Don't create your image inside the paintComponent method. Do it in the constructor.

    public class GameBoard extends JPanel { 
        ImageIcon img;
        public GameBoard() {
            img = new ImageIcon(...);
        }
    
  4. pack() your frame, don't setSize(), and the preferred size of the JPanel will be respected (by your override getPreferredSize()).

  5. You can just use getWidth() and getHeight() after override getPreferredSize()

    drawImage(bg.getImage(), 0, 0, getWidth(), getHeight(), this);
    

Work on all these things, if it doesn't help, post a runnable example we can test out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top