简体   繁体   English

JFrame仅打开关闭,最小化和调整大小按钮,直到调整窗口大小为止

[英]JFrame opens only the close, minimize and resize buttons until I resize the window

I'm making a game in Java and the game window doesn't open properly when i run the code. 我正在用Java开发游戏,运行代码时游戏窗口无法正确打开。 I can resize it and make it the right size, but that's kinda annoying to do every time. 我可以调整它的大小并将其调整为正确的大小,但这每次都很烦人。

Here's the code for the window and I also added a picture to show how the window opens. 这是窗口的代码,我还添加了图片以显示窗口的打开方式。

import javax.swing.*;
import java.awt.*;

public class Window extends Canvas {

    private static final long serialVersionUID = 573860602378245302L;

    public Window(int width, int height, String title, Game game){
        JFrame frame = new JFrame(title);

        frame.setPreferredSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(true);
        frame.setLocationRelativeTo(null);
        frame.add(game);
        frame.setVisible(true);
        game.start();
    }
}

在此处输入图片说明

There are few ways you can make a JFrame of a particular size. 制作特定大小的JFrame的方法很少。 frame.setPreferredSize() is NOT one of those ways. frame.setPreferredSize()不是这些方式之一。

You can call setSize(int width, int height) on JFrame like this: 您可以像这样在JFrame上调用setSize(int width, int height)

import javax.swing.JFrame;

public class JFrameSize
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
  }
}

Or you can set preferred size of the contents (a JPanel in below example) of JFrame and call pack() on JFrame like this: 或者,您可以设置JFrame内容的首选大小(在下面的示例中为JPanel ),并在JFrame上调用pack() ,如下所示:

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Dimension;

public class JFrameSize2
{
  public static void main(String[] args)
  {
    JPanel panel = new JPanel();
    panel.setPreferredSize(new Dimension(400, 300));

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM