gpt4 book ai didi

java - 我的 Java swing 主机上没有任何内容

转载 作者:行者123 更新时间:2023-12-01 20:53:44 25 4
gpt4 key购买 nike

我正在阅读《Core Java Volume I- Fundamentals 9th Edition- Horstmann, Cay S. & Cornell, Gary_2013》一书,并且仍在学习 Java,特别是 Swing 和 AWT,但我对书中的一项任务有疑问。任务是构建一个包含 3 个扇区 Northern 的框架,并包含用户名和密码。将文本区域居中,并用按钮向南。主框架采用边框布局。当用户输入用户名和密码并单击“插入”按钮时,用户名和密码将被输入到文本区域中。这是结果的图片: enter image description here
所以当我尝试这样做时,我得到一个像这样的小窗口: enter image description here


我哪里错了?我无法理解这一点。这是扩展 JFrame 的类

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

public class MainFrame extends JFrame {
public MainFrame() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width;
int height = screenSize.height;
setSize(width / 2, height / 2);
setLayout(new BorderLayout());

JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(2,2));
northPanel.add(new JLabel("Username: ", JLabel.RIGHT));
JTextField textField = new JTextField();
northPanel.add(textField);
northPanel.add(new JLabel("Password: ", JLabel.RIGHT));
JPasswordField passwordField = new JPasswordField();
northPanel.add(passwordField);

add(northPanel, BorderLayout.NORTH);


JTextArea textArea = new JTextArea(8, 20);
JScrollPane centerPanel = new JScrollPane(textArea);


add(centerPanel, BorderLayout.CENTER);

JPanel southPanel = new JPanel();
JButton insertButton = new JButton("Insert");
southPanel.add(insertButton);

add(southPanel, BorderLayout.SOUTH);
}
}

我的 MainTestMethod 是这样的:

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

public class MainTestProgram {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle("Krisko Beatz");
mainFrame.setVisible(true);
mainFrame.setLocation(500, 100);
}
}

最佳答案

JFrame mainFrame = new JFrame(); 更改为 JFrame mainFrame = new MainFrame();

您可以删除...

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width;
int height = screenSize.height;
setSize(width / 2, height / 2);

相反,在构造函数的末尾调用 pack();,它将生成更可靠的 UI 大小

关于java - 我的 Java swing 主机上没有任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42774127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com