0

I'm making a very simple game using Java and Swing, however the coordinates (including width and height) are off by a small amount (between 3 and 30 pixels).

Here is my code

public class GraphicsWindow extends JFrame {
    public GraphicsWindow(int x, int y) {
        this.setTitle("To Be updated");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(x, y);
        this.setVisible(true);
    }

    @Override
    public void paint(Graphics gr) {
        Graphics2D g = (Graphics2D)gr;
        g.drawLine(0, 0, 0, 0); //should draw one pixel in the top-left
        g.drawLine(40, 40, 40, 40); //draws correctly, but not at 40, 40
        g.dispose();
    }
}

I have a hypothesis that that it is including the title bar and border in the coords however I'm not sure if this is correct, and even if it is, the titlebar is dependant on the system so I cannot just program constants in to account for it.

Thanks in advance.

P.S I'm open to title suggestions.

Jachdich
  • 782
  • 8
  • 23
  • 4
    Don't paint on a JFrame. Paint on a JPanel inserted in the JFrame's content pane. And use the correct method to paint: paintComponent(). – JB Nizet Nov 19 '19 at 20:21
  • @JBNizet so I should create a new class extending JPanel and put my code in that, and add it to the JFrame as a widget? – Jachdich Nov 19 '19 at 20:24
  • 1
    Yes, that's what you should do. – JB Nizet Nov 19 '19 at 20:25
  • @JBNizet thankyou I shall try that – Jachdich Nov 19 '19 at 20:25
  • 2
    Read the section from the Swing tutorial on [Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) for more information and working examples. For example you also need to 1) override getPreferredSize() and invoke super.paintComponent(...). – camickr Nov 19 '19 at 20:26

0 Answers0