【问题标题】:Using JTextField makes everything else dissappear使用 JTextField 使其他一切都消失了
【发布时间】:2016-04-28 23:10:35
【问题描述】:

我尝试在 Java 中使用 Swing 放置一个文本字段和一个按钮和标签。我成功添加了标签和按钮,但是如果我尝试添加文本字段,孔框是空白的,所以什么都没有显示,而不是甚至按钮或标签。 我做错了什么?

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

public class SwingPartOne extends JFrame {

public static void main(String[] args) {
    new SwingPartOne();
}

public SwingPartOne(){
    this.setSize(800,800);
    this.setLocationRelativeTo(null);
    this.setVisible(true);

    Toolkit tk = Toolkit.getDefaultToolkit();

    Dimension dim = tk.getScreenSize();

    int xPos = (dim.height / 2) - (this.getHeight() / 2);
    int yPos = (dim.width / 2) - (this.getWidth() / 2);

    this.setResizable(false);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.setTitle("First Jframe");


    JPanel thePanel = new JPanel();

    JLabel label1 = new JLabel("Some random text .");

    label1.setText("New text.");

    label1.setToolTipText("Surprize!");

    JButton thebutton1 = new JButton("BOOM!");

    JTextField textField = new JTextField("Some text" , 15);
    textField.setColumns(5);
    textField.setSize(200,200);
    textField.setText("Some random text");

    thePanel.add(label1);
    thePanel.add(textField);
    thePanel.add(thebutton1);
    this.add(thePanel);






}
}

【问题讨论】:

  • 在构造函数的末尾调用this.setVisible(true),这样它就可以validate。另外,其他一些注意事项:1)textField.setSize(200,200); 不会做太多,而是覆盖它的getPreferredSize 方法(仅当您确实需要时)。 2) 要使框架居中,您也可以简单地调用setLocationRelativeTo(null)。无需计算xPosyPos
  • BewaresetResizable(false).

标签: java swing jframe


【解决方案1】:

我在 LuxxMiner 的帮助下将this.setVisible(true) 放在最后解决了这个问题。

> 在构造函数的末尾调用 this.setVisible(true) 以便它可以验证。另外,其他一些注意事项: 1) textField.setSize(200,200);不会做太多,而是覆盖它的 getPreferredSize 方法(仅当您确实需要时)。 2) 要使框架居中,您也可以简单地调用 setLocationRelativeTo(null)。无需计算 xPos 和 yPose

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2014-09-09
    • 2017-02-21
    • 2021-10-17
    相关资源
    最近更新 更多