我正在尝试用 Swing 编写一个小型 UI 程序。我需要一些文本字段,但是定义一个新的文本字段或文本区域(我什至不必将其添加到框架中)将随机阻止它们本身以及代码中在它们之后添加的任何内容出现在屏幕上。
我可以重新编译相同的代码而不做任何更改,也许 1/3 的时间它会正常工作。是什么导致了这个问题?有什么办法可以改变它吗?
import java.awt.*;
import javax.swing.*;
public class ThisApp
{
public static void main(String [] Args)
{
new ThisUI();
}
}
class ThisUI extends JFrame //implements ActionListener
{
public ThisUI()
{
setTitle("ThisApp - Best in the business");
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLayout(new GridLayout(2,1));
JButton cat = new JButton("Cat");
this.add(new JButton("Button"));
this.add(new JTextField("CAT CAT",10));
}
}
问题是您在框架可见后向框架添加组件,并且不调用布局管理器,因此所有组件的大小均为 0,因此没有任何内容可绘制。
将所有组件添加到框架后,必须使框架可见。
所以你的代码结构应该是这样的:
setTitle("ThisApp - Best in the business");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,1));
JButton cat = new JButton("Cat");
this.add(new JButton("Button"));
this.add(new JTextField("CAT CAT",10));
setSize(300, 200);
setLocationRelativeTo( null );
setVisible(true);