java - 为什么 setSize 在 Java 中不起作用

标签 java swing user-interface

我正在尝试打开一个具有特定 WINDOW_WIDTHWINDOW_HEIGHT 的窗口。

/**
 * Program to calculate a tip based on a restaurant bill
 * @author Nick Gilbert
 */
import javax.swing.*;
import java.awt.*;
public class TipCalculator extends JFrame {
    private JFrame frame1;
    private JLabel label1;
    private JPanel panel1;
    private JTextField askBill;
    private final int WINDOW_WIDTH = 400;   // Window width
    private final int WINDOW_HEIGHT = 300;  // Window height

    /**
     * Constructor
     */
    public TipCalculator(){
        setTitle("Tip Calculator!");
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        panel1 = new JPanel();
        label1 = new JLabel("Enter bill:");
        askBill = new JTextField(10);

        panel1.add(label1);
        panel1.add(askBill);
        add(panel1, BorderLayout.NORTH);

        pack();
        setVisible(true);
    }
    public static void main(String[] args) {
        new TipCalculator();
    }
}

但是,当我运行此命令时,我使用 setSize 方法指定的宽度和高度没有效果,我不知道为什么

最佳答案

您正在调用pack

setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
//...
pack();

来自JavaDocs ...

public void pack()
Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.

If the window and/or its owner are not displayable yet, both of them are made displayable before calculating the preferred size. The Window is validated after its size is being calculated.

这实际上是调整窗口大小的首选方法,因为它考虑到了平台之间的差异。它还意味着窗口的可视空间(窗口边框内的区域)与其内容的首选大小相匹配。

调用 setSize 使窗口具有指定的大小,这意味着内容将具有指定的大小 - 窗口边框,对于不同的外观和感觉以及平台,该大小会有所不同。

关于java - 为什么 setSize 在 Java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22676020/

相关文章:

qt - 选择跨平台的 GUI 技术

java - Entity.UserBean 无法转换为Entity.UserBean

java - 使用 jni 和 OpenCV 创建的带有 lib 的 undefined symbol

java - 将 JList 复制到 arrayList 时出错

java - JPanel 自己的坐标

html - '.row' 中整个一半的 '.col-md-6' 的 CSS 背景

java - 如何在 Android Studio 中查看哪些文件没有保存?

java - 将数字实体转换为可读格式

java - 自定义滚轮监听器阻止 ScrollPane 滚轮监听器

使用 Espresso 进行 Android 移动应用程序 UI 测试 - Chrome 停止运行