我正在使用Java編寫此遊戲,並且我只是將所有與窗口有關的代碼從基於java.awt的java代碼重寫爲javax.swing。不久之後,我意識到事情現在有點複雜了,所以我做了一些研究,並找出瞭如何繪製事物,如何設置JFrame的大小等。但由於某些原因,我的JFrame的大小總是比我指定的尺寸大10個像素。在這種情況下,我希望它是640×640像素。我的JFrame總是變成幾個像素太大。
這裏是我的代碼:
package chrononaut;
import java.awt.*;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
@SuppressWarnings("serial")
public class GameJFrame extends JFrame
{
//Background color:
static Color bgrCol = new Color(12, 4, 64);
//Size:
final static int size = 640;
//The component that does the actual drawing:
static GameJComp drawingComp = new GameJComp();
//Constructor:
public GameJFrame()
{
//Calling super() and setting the title:
super("Chrononaut");
//Setting icon image:
try
{
Image icon = ImageIO.read(getClass().getResource("/icon/icon 1.png"));
setIconImage(icon);
}
catch (IOException e) {}
//make it closable:
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting the size:
Container c = getContentPane();
Dimension d = new Dimension(size, size); //for some reason, it goes 10 pixels beyond the given values
c.setPreferredSize(d);
pack();
//Adding the drawing component to the content pane:
getContentPane().add(drawingComp);
//Making sure the window size stays constant:
setResizable(false);
//Centering position:
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension s = tk.getScreenSize();
setLocation(s.width/2-getWidth()/2, s.height/2-getHeight()/2);
//Background color:
setBackground(bgrCol);
//Make it visible:
setVisible(true);
}
public void drawAll()
{
drawingComp.drawAll();
}
public void closeGame()
{
dispose();
System.exit(0);
}
}
當我運行它,JFrame的邊界內的空間似乎有一個大小爲650個像素,而不是640,甚至當我調用了setPreferredSize(d)。 我試過讓Dimension d = new Dimension(size - 10,size - 10);這似乎工作,但我不知道它會在其他平臺上的天氣。 我在網上的其他地方沒有看到這個問題,所以我完全不知道它爲什麼這樣做。 :(
謝謝!有效! :D – 2014-11-01 12:10:24
@MagnusAppel是的,這是一個API的痛苦;) – MadProgrammer 2014-11-01 12:11:29