【问题标题】:Why AWT frame's text field is not appearing?为什么没有出现 AWT 框架的文本字段?
【发布时间】:2021-09-27 15:28:57
【问题描述】:
import java.awt.*;
import java.awt.event.*;

public class example3 extends Frame implements ActionListener
{
TextField t;
Button b;
    example3()
    {
        t = new TextField();
        t.setBounds(20,20,170,20);
        add(t);

        b = new Button("click me");
        b.setBounds(100,120,80,30);
        add(b);
        b.addActionListener(this);
        
        setLayout(null);
        setSize(300,300);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
        t.setText("welcome");
    }

    public static void main(String args[])
    {
        example3 obj = new example3();
    }
}

最初我向框架对象添加了一个文本字段,我还创建了一个按钮并将其添加到框架对象,但我没有得到正确的输出。

当我执行这个程序时文本字段没有出现。为什么?

我得到这样的输出:enter image description here

【问题讨论】:

  • 你认为帧上的 0、0 点是什么?所以……你不觉得 20、20 是一个相当糟糕的位置吗?此外,您还可以在图片中看到部分文本字段。
  • 我会说您的问题从setLayout(null); 开始,但我还要说使用 AWT 可能是一个不好的起点。我建议从 Creating a GUI With JFC/SwingLaying Out Components Within a Container 开始,但最好从 JavaFX 开始
  • 远离 AWT。使用 Swing。

标签: java awt frame


【解决方案1】:

我只想建议第 11 行的一项更改,即 根据您的要求增加 setBounds 的 x 坐标和 y 坐标值,因为您的代码可以正常工作,但该字段不可用在可见的位置。

例如:- 你的代码:- t.setBounds(20,20,170,20); 更改后:- t.setBounds(50,50,170,20);

import java.awt.*;
import java.awt.event.*;

public class example3 extends Frame implements ActionListener
{
TextField t;
Button b;
    example3()
    {
        t = new TextField();

        
       // t.setBounds(20,20,170,20);
       //Changes has been done,here.
       t.setBounds(50,50,170,20);
        add(t);



        

        b = new Button("click me");
        b.setBounds(100,120,80,30);
        add(b);
        b.addActionListener(this);
        
        setLayout(null);
        setSize(300,300);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {
        t.setText("welcome");
    }

    public static void main(String args[])
    {
        example3 obj = new example3();
    }
}

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多