Hi, I have the following code to display a game in a window (Frame) or applet mode:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Game extends Applet {
private boolean isApplet;
public Game() {
this.isApplet = true;
}
public void init() {
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, 640, 480);
g.setColor(Color.red);
g.drawRect(0, 0, 640, 480);
// g.setColor(Color.green);
// g.drawRect(0, 0, 640 - 3, 480 - 33);
}
public void update(Graphics g) {
}
public void buildFrame() {
Frame f = new Frame("Game");
// Add an window adapter to allow user close it.
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setSize(640, 480);
f.setResizable(false);
// Get current screen resolution to adjust the frame in the middle
// of the user desktop.
Dimension dimension = getToolkit().getScreenSize();
Rectangle rectangle = f.getBounds();
// Put the frame centered in the user desktop.
f.setLocation((dimension.width - rectangle.width) / 2,
(dimension.height - rectangle.height) / 2);
// Add the applet to frame.
f.add(this);
// Show it!
f.setVisible(true);
this.isApplet = false;
// Call applet init method.
this.init();
}
public static void main(String[] args) {
Game g = new Game();
g.buildFrame();
}
}
When running as application it starts in the main method that calls the buildFrame method to put the applet inside of it.
I have created a 640x480 pixels window and to make sure the size is correct I have drawn a rectangle with (0,0,640,480) but for my surprise it does not appear in the right and bottom edges.
To make the full rectangle appear in the screen I had to put the following code:
g.drawRect(0, 0, 640 - 3, 480 - 33);
Why this happens? The same problem happens when running in the browser (applet mode).
I also noticed that the result is different when running in Windows (I’m using Linux). I had to put (-5) in the right corner to make it appear.
The question is: is there a way to make the code above display a real 640x480 display for both applet/application and plataform independent?
Thanks!