Reputation: 141
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?
Upvotes: 3
Views: 6663
Reputation: 576
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;
Upvotes: 0
Reputation: 11
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
Upvotes: 1
Reputation: 11
public void init() {
setSize(400, 600);
}
instead of setting the size in the run method do it on the init!
Upvotes: 1
Reputation: 1003
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.
Upvotes: 1