如何解决我的JFrame总是变得太大了几个像素。?
这是与setResizable(false);
您尝试设置窗口大小后使用有关的问题。
问题是(至少在Windows上)可调整大小的窗口和不可调整大小的窗口之间边框的大小不同。
致电setResizable
前致电pack
如果您想要更好(通常更可靠)的窗口居中方法,请考虑使用
setLocationRelativeto(null);
代替
setLocation(s.width/2-getWidth()/2, s.height/2-getHeight()/2);
Toolkit.getScreenSize
没有考虑任务栏占用的空间…
解决方法
我正在用Java进行游戏,只是将所有与窗口相关的代码从基于java.awt重写为javax.swing。不久之后,我意识到事情变得有些复杂了,因此我做了一些研究,发现了如何绘制事物,如何设置JFrame的大小等。但是由于某种原因,我的JFrame的大小总是比我指定的尺寸超出10像素。在这种情况下,我希望它是640
x 640像素。
这是我的代码:
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);
}
}
当我运行它时,即使我调用setPreferredSize(d),JFrame边框内的空间似乎也只有650像素而不是640像素。我尝试使尺寸d
=新尺寸(size-10,size-10);
这似乎确实有效,但是我不知道在其他平台上会遇到什么天气。我在网络上其他任何地方都没有看到这个问题,所以我完全不知道为什么会这样做。:(
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。