我想知道为什么当我输入此代码而不调整窗口大小时,我看不到任何内容:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GolfScoresGUI
{
public static void main(String[] args)
{
JFrame frame = new JFrame("GolfScoresGUI");
JLabel label = new JLabel("Did you score it? ");
JTextField textField = new JTextField(10);
frame.setVisible(true);
frame.getContentPane().add(textField);
}
}
最佳答案
将组件添加到调用 setPreferredSize
的面板中,将该面板添加到框架中并调用 JFrame.pack()。
JFrame.pack() 更新框架的大小,以在给定其所包含元素的大小的情况下采用最小可能的大小。
如果你不调用它,大小将类似于 0x0,这解释了为什么你看不到任何东西。
JFrame frame = new JFrame("GolfScoresGUI");
JPanel panel=new JPanel();
panel.setPreferredSize(new Dimension(600,400)); // Not mandatory. Without this, the frame will take the size of the JLabel + JTextField
frame.add(panel);
JLabel label = new JLabel("Did you score it? ");
JTextField textField = new JTextField(10);
panel.add(label);
panel.add(textField);
frame.setVisible(true);
frame.pack();
编辑
顺便说一句,您还应该添加此行,以便您的应用程序在关闭框架时停止:
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
关于java - 如果我不调整窗口大小,为什么窗口太小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16200040/