[java] origin for graphics context off screen

Started by
2 comments, last by Aldacron 17 years, 12 months ago
I am writing a basic game in java. Every renderable object maintains its own coordinates and size. Each object assumes that the origin (0, 0) is where it should be, namely in the upper left corner of the screen. It seems that the origin is not in the upper left corner but rather somewhere in the negatives. Thus, if I try to draw in object at the origin, it does not appear on screen. Here is the code I use to obtain the Graphics object used for rendering.

private void renderObjects()
	{
		Graphics g = buffer.getDrawGraphics();
		g.setColor(frame.getBackground());
		
		g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
		g.setColor(Color.black);
		g.setFont(new Font("Courier", Font.PLAIN, 28));
		g.drawString("Score: " + player.getScore() + "  Hits: " + player.getHits() + "  Misses: " + player.getMisses(), 100, 100);

		for(Creature creature: creatures)
		{
			creature.render(g);
		}
		
		buffer.show();
		g.dispose();
	}


The object "buffer" was obtained and stored in this code:

frame = new JFrame("Duck Hunt");
frame.setPreferredSize(new Dimension(800, 600));
frame.setBackground(Color.white);
frame.getContentPane().addMouseListener(new ClickHandler());

				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
				
frame.createBufferStrategy(2);
buffer = frame.getBufferStrategy();
				
frame.setVisible(true);


Any help or suggetions is appreciated. Thanks.
Advertisement
I can't tell what is wrong from the code shown, but the origin is in the upper-left corner. You will have to show more code to figure it out. Try a simple test.
import java.util.*;import java.awt.*;import javax.swing.*;public class Test extends JPanel {    public void paint(Graphics g) {        g.fillRect(10, 10, 100, 100);    }    public static void main(String args[]) {        JFrame f = new JFrame();        f.getContentPane().add(new Test());        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        f.setSize(300, 300);        f.show();    }}

This will show you where the origin is.
"None of us learn in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!" - Michael Abrash[JavaGaming.org][The Java Tutorial][Slick][LWJGL][LWJGL Tutorials for NeHe][LWJGL Wiki][jMonkey Engine]
I figured it out.

The graphics context of a JFrame includes the title bar. When I do frame.setUndecorated(true), the problem is fixed, however, I can't move the window (not a big issue).

Thanks for your help though.
Don't draw directly to the JFrame. Add a JPanel, or an AWT Canvas, to the frame and draw to that instead. Then you can keep the title bar on the frame and still use (0,0) as the origin.

This topic is closed to new replies.

Advertisement