3

I want to define the size of the window, but I did not find a clean way to do it. SetSize() gives a strange result:

public class Test extends GraphicsProgram {

    public void run() {

        setSize(400, 600);
        add(new GLabel("Width: " + getWidth(), 30, 30));
        add(new GLabel("Height: " + getHeight(), 30, 50));
    }

}

The result is 384 x 542. The gap is always the same (-16 x -58), so it's easy to build a work around. Is there a way to define the size in useful pixels directly?

Robin Green
  • 32,079
  • 16
  • 104
  • 187
A_rnO
  • 141
  • 1
  • 5
  • I'd definitely be interested in a way to set the canvas size as well since I had this very same issue earlier tonight, there were workarounds but they were clunky modifications to startercode that shouldn't be necessary. –  Nov 14 '12 at 13:37
  • Canvas size is Application Size + px for menu window height/width. It looks like for me its (x,y)(18px,70px ) for menu and bar modifications. Using setSize(x+mod,y+mod) you can get your coordinate system fixed. –  Nov 14 '12 at 13:49
  • Agreed that I would rather be able to set the canvas size to the usable size directly. There should be some good reasons to have it like that, like integration in a web page. – A_rnO Nov 14 '12 at 14:42

4 Answers4

1

I found a solution to this while studying the code of a Stanford course project (breakout). GraphicsProgram is not constructed according to its fields, WIDTH, HEIGHT, EAST, CENTER etc, automatically. Therefore we need a resize() to set the window size which acm.program.GraphicsProgram inherits from java.applet.Applet. Simply adding a resize() and pause() will do the work.

public class Test extends GraphicsProgram {
    private static final int WIDTH = 400;
    private static final int HEIGHT = 600;
    private static final int PAUSE = 10; // or whatever interval you like

    public void run() {
        this.resize(WIDTH,HEIGHT);
        pause(PAUSE);
        // game logic here
        ...
    }

}

The pause() is necessary as the resize takes time. It avoids the mis-displacement of components if you are adding them right after resizing.

Sophia Feng
  • 993
  • 11
  • 16
1
public void init() {

    setSize(400, 600);


}

instead of setting the size in the run method do it on the init!

1

After class:
public static final int APPLICATION_WIDTH = 900; // x size of window

Before run:
public static final int APPLICATION_HEIGHT = 540; // y size of window

robyaw
  • 2,274
  • 2
  • 22
  • 29
john
  • 11
  • 1
0

No need for setSize or resize.

You just need to add this two public variables:

/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;

and these two if you need exactly WIDTH and HEIGHT to use:

/** Dimensions of window (usually the same) */
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;