除了我的 JText 之外,JLabel 没有显示

JLabel Not Showing Up Besides My JText

我不知道如何在我的按钮或文本字段之外放置文本,当我为标签和文本字段(从互联网复制的)制作单独的代码时它正在工作,但不是在这种情况下,请告诉我如何让它工作?我有一个想法,比如我可能必须使用一些框架或一些布局,但有必要吗?请只是基础知识。谢谢。 :

public class UIClass extends JFrame {

public UIClass()
{   super("GUIPart1");
    super.setBounds(50,50,1000,700);
    super.setResizable(true);
    super.setVisible(true);
    super.setDefaultCloseOperation(EXIT_ON_CLOSE);
    // Button
    JButton btn1=new JButton();
    btn1.setBounds(50,50, 100, 50);
    super.add(btn1);
    super.setLayout(null);
    btn1.setText("Test"); 

    //TextField
    JTextField tf1=new JTextField(15);
    super.add(new JLabel("Label :"));
    super.add(tf1);
    tf1.setBounds(100,100,200,200);


    //OptionPane
    JOptionPane text=new JOptionPane();
    String Message=JOptionPane.showInputDialog("My Message");
    JOptionPane.showMessageDialog(null,"Thank you");


}

public static void main(String args[])
{
    UIClass u=new UIClass();

}
}

你应该打电话给

this.repaint();

最后。我不建议在 JavaDoc 中使用 setBounds 它显示为:

This method changes layout-related information, and therefore, invalidates the component hierarchy.

它在您调整大小时 window 时显示。这对带有

的代码有效
JLabel jl=new JLabel("Label : "); jl.setBounds(300,300,400,400); super.add(jl);

正如您在评论中提到的...

在您的原始代码中,您明确将容器布局设置为空。 在这种情况下,您必须指定您添加的每个其他组件的位置和大小,并且您只为按钮和文本字段组件指定了位置和大小。

您在评论中发布的代码使用 BorderLayout 作为 LayoutManager,它会根据他的策略自动调整每个组件的大小和位置。

我强烈建议您学习如何使用 LayoutManagers,因为它们是 Java UI 环境中的关键组件,至少 BorderLayout 和 GridLayout,因为如果您的应用程序不是太复杂他们应该做的伎俩。